mirror of
https://github.com/kuhyx/steam-backlog-enforcer.git
synced 2026-11-28 13:29:16 +01:00
Compare commits
8 Commits
db44ca5b0b
...
f804a4987f
| Author | SHA1 | Date | |
|---|---|---|---|
| f804a4987f | |||
| 103f072509 | |||
| 3e53cf3686 | |||
| 749f12ca27 | |||
| ce818db86c | |||
| 7721b8716e | |||
| 681ab14481 | |||
| 444f619e6d |
2
.github/workflows/python-tests.yml
vendored
2
.github/workflows/python-tests.yml
vendored
@ -59,7 +59,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 26.13.0
|
node-version: 26.13.1
|
||||||
cache: pnpm
|
cache: pnpm
|
||||||
cache-dependency-path: web/pnpm-lock.yaml
|
cache-dependency-path: web/pnpm-lock.yaml
|
||||||
|
|
||||||
|
|||||||
@ -176,11 +176,9 @@ disable = [
|
|||||||
[tool.pylint.design]
|
[tool.pylint.design]
|
||||||
min-public-methods = 0
|
min-public-methods = 0
|
||||||
max-module-lines = 250
|
max-module-lines = 250
|
||||||
# 15 = the widest persisted record (config.Config). Config, State and
|
# 10, the repo's original value: wider persisted records group their
|
||||||
# PlaytimeState are flat JSON files the live daemon reads and writes; WebGame
|
# fields into nested dataclasses and keep a flat on-disk JSON shape.
|
||||||
# is the UI's row shape. Splitting them under 10 would change the on-disk shape
|
max-attributes = 10
|
||||||
# or hide it behind property forwarders written only for this check.
|
|
||||||
max-attributes = 15
|
|
||||||
|
|
||||||
[tool.pylint.typecheck]
|
[tool.pylint.typecheck]
|
||||||
generated-members = [
|
generated-members = [
|
||||||
|
|||||||
@ -62,15 +62,15 @@ def record_assignment(
|
|||||||
stamp = at or _now_iso()
|
stamp = at or _now_iso()
|
||||||
state.current_app_id = app_id
|
state.current_app_id = app_id
|
||||||
state.current_game_name = game_name
|
state.current_game_name = game_name
|
||||||
state.current_assigned_at = stamp
|
state.assignment.current_assigned_at = stamp
|
||||||
state.last_assigned_at[str(app_id)] = stamp
|
state.assignment.last_assigned_at[str(app_id)] = stamp
|
||||||
if not state.enforcement_started_at:
|
if not state.enforcement_started_at:
|
||||||
state.enforcement_started_at = stamp
|
state.enforcement_started_at = stamp
|
||||||
|
|
||||||
|
|
||||||
def last_assigned_epoch(state: State, app_id: int) -> float:
|
def last_assigned_epoch(state: State, app_id: int) -> float:
|
||||||
"""Return when *app_id* was last assigned, ``0.0`` if never (sorts first)."""
|
"""Return when *app_id* was last assigned, ``0.0`` if never (sorts first)."""
|
||||||
return iso_to_epoch(state.last_assigned_at.get(str(app_id), "")) or 0.0
|
return iso_to_epoch(state.assignment.last_assigned_at.get(str(app_id), "")) or 0.0
|
||||||
|
|
||||||
|
|
||||||
def assignment_baseline(state: State, app_id: int) -> str:
|
def assignment_baseline(state: State, app_id: int) -> str:
|
||||||
@ -86,7 +86,7 @@ def assignment_baseline(state: State, app_id: int) -> str:
|
|||||||
if pick.get("app_id") == app_id and pick.get("started_at"):
|
if pick.get("app_id") == app_id and pick.get("started_at"):
|
||||||
return str(pick["started_at"])
|
return str(pick["started_at"])
|
||||||
if app_id == state.current_app_id:
|
if app_id == state.current_app_id:
|
||||||
return state.current_assigned_at
|
return state.assignment.current_assigned_at
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
|
|
||||||
@ -158,5 +158,5 @@ def release_game(state: State, game: GameInfo) -> None:
|
|||||||
for pick in state.manual_picks:
|
for pick in state.manual_picks:
|
||||||
if pick.get("app_id") == game.app_id and not pick.get("released_at"):
|
if pick.get("app_id") == game.app_id and not pick.get("released_at"):
|
||||||
pick["released_at"] = now
|
pick["released_at"] = now
|
||||||
state.released_at[str(game.app_id)] = now
|
state.assignment.released_at[str(game.app_id)] = now
|
||||||
state.skip_for_days(game.app_id, RELEASE_COOLDOWN_DAYS)
|
state.skip_for_days(game.app_id, RELEASE_COOLDOWN_DAYS)
|
||||||
|
|||||||
@ -168,12 +168,12 @@ def build_rules(rules: PlaytimeRules) -> dict[str, Any]:
|
|||||||
# Read off the rules, never re-resolved: resolving a second time here
|
# Read off the rules, never re-resolved: resolving a second time here
|
||||||
# is what would let this view report a budget the daemon is not
|
# is what would let this view report a budget the daemon is not
|
||||||
# enforcing. See _budget_resolve's "one seam".
|
# enforcing. See _budget_resolve's "one seam".
|
||||||
"budget_reason": rules.budget_reason,
|
"budget_reason": rules.breakdown.reason,
|
||||||
"bonuses": {
|
"bonuses": {
|
||||||
"base": rules.base_seconds,
|
"base": rules.breakdown.base_seconds,
|
||||||
"workout": rules.workout_seconds,
|
"workout": rules.breakdown.workout_seconds,
|
||||||
"leetcode": rules.leetcode_seconds,
|
"leetcode": rules.breakdown.leetcode_seconds,
|
||||||
"reading": rules.reading_seconds,
|
"reading": rules.breakdown.reading_seconds,
|
||||||
},
|
},
|
||||||
# The registry, in its order: what each earner adds today and what it
|
# The registry, in its order: what each earner adds today and what it
|
||||||
# would add once done. The bar renders "+<icon><size>" for every
|
# would add once done. The bar renders "+<icon><size>" for every
|
||||||
@ -183,7 +183,7 @@ def build_rules(rules: PlaytimeRules) -> dict[str, Any]:
|
|||||||
{
|
{
|
||||||
"name": earner.name,
|
"name": earner.name,
|
||||||
"label": earner.label,
|
"label": earner.label,
|
||||||
"earned_seconds": rules.earned_seconds.get(earner.name, 0.0),
|
"earned_seconds": rules.breakdown.earned_seconds.get(earner.name, 0.0),
|
||||||
# A full day pays up to the tutor's 60 credited units.
|
# A full day pays up to the tutor's 60 credited units.
|
||||||
"bonus_seconds": _most(earner) * 60,
|
"bonus_seconds": _most(earner) * 60,
|
||||||
}
|
}
|
||||||
|
|||||||
84
steam_backlog_enforcer/_config_groups.py
Normal file
84
steam_backlog_enforcer/_config_groups.py
Normal file
@ -0,0 +1,84 @@
|
|||||||
|
"""Field groups of :class:`~config.Config` and :class:`~config.State`.
|
||||||
|
|
||||||
|
Each group is stored flat in its record's JSON file (see ``_flat_record``):
|
||||||
|
the keys below are the exact keys of ``config.json`` / ``state.json``.
|
||||||
|
A leaf module, so ``config`` can import it.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class EarnSources:
|
||||||
|
"""Where each earned-time bonus is read from (``config.json``)."""
|
||||||
|
|
||||||
|
book_ledger_path: str = "~/.local/share/book_guard/ledger.json"
|
||||||
|
"""book-guard's signed ledger: the reading hour's only transport."""
|
||||||
|
workout_status_url: str = "http://127.0.0.1:8770/api/status"
|
||||||
|
"""Where to ask whether today has a counted workout. Loopback only."""
|
||||||
|
workout_log_path: str = "~/src/screen-locker/screen_locker/log.json"
|
||||||
|
"""screen-locker's log.json; a change re-asks that URL at once."""
|
||||||
|
leetcode_ledger_path: str = "~/.local/share/leetcode_guard/ledger.json"
|
||||||
|
leetcode_status_url: str = "http://127.0.0.1:8771/api/status"
|
||||||
|
"""LeetCode's transports: ledger first, this loopback URL as fallback."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PlaytimePolicy:
|
||||||
|
"""What counts against the daily gaming budget (``config.json``)."""
|
||||||
|
|
||||||
|
count_launcher_processes: bool = True
|
||||||
|
"""Whether time spent in non-Steam launchers counts against the budget.
|
||||||
|
|
||||||
|
Set False if a launcher legitimately idles in the tray all day. Leaving it
|
||||||
|
True is the safer default: under-counting is the failure mode that quietly
|
||||||
|
defeats the budget entirely.
|
||||||
|
"""
|
||||||
|
counted_processes: list[dict[str, Any]] | None = None
|
||||||
|
"""Non-Steam games that count against the budget, beyond the launcher set.
|
||||||
|
|
||||||
|
Each entry is ``{"id": ..., "label": ..., "names": [...]}``. ``None`` means
|
||||||
|
"use the built-in defaults" (osu!lazer); an explicit ``[]`` means "none",
|
||||||
|
which is why this is not simply an empty list. Parsed and validated by
|
||||||
|
``leisure_watch.procscan`` (once ``_counted_procs``) — the field exists
|
||||||
|
here only so that ``save()`` round-trips a hand-edited list instead of
|
||||||
|
dropping it.
|
||||||
|
|
||||||
|
Deliberately separate from ``LAUNCHER_PROCESS_NAMES``: that frozenset is
|
||||||
|
also the total-block kill list, so adding a game there has side effects
|
||||||
|
this list does not.
|
||||||
|
"""
|
||||||
|
playtime_enforcement: bool = True
|
||||||
|
"""Master switch for the daily gaming budget.
|
||||||
|
|
||||||
|
Disabling stops the cutoff but never strands a live block — the release
|
||||||
|
path runs regardless, so "disabled" cannot come to mean "blocked forever".
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class LegacyManualPick:
|
||||||
|
"""Legacy single-slot manual pick, migrated into ``manual_picks`` on load.
|
||||||
|
|
||||||
|
Stored as ``manual_pick_app_id`` / ``_game_name`` / ``_started_at`` so an
|
||||||
|
older ``state.json`` still deserialises; blanked once migrated.
|
||||||
|
"""
|
||||||
|
|
||||||
|
app_id: int | None = None
|
||||||
|
game_name: str = ""
|
||||||
|
started_at: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class AssignmentTimes:
|
||||||
|
"""When games were assigned and released (``state.json``)."""
|
||||||
|
|
||||||
|
current_assigned_at: str = ""
|
||||||
|
"""ISO time the current game was assigned; unlocks after it release it."""
|
||||||
|
last_assigned_at: dict[str, str] = field(default_factory=dict)
|
||||||
|
"""``str(app_id)`` → ISO time of its latest assignment (pick ordering)."""
|
||||||
|
released_at: dict[str, str] = field(default_factory=dict)
|
||||||
|
"""``str(app_id)`` → ISO time it was released below 100% (tampering)."""
|
||||||
@ -13,6 +13,7 @@ import json
|
|||||||
import sys
|
import sys
|
||||||
|
|
||||||
from steam_backlog_enforcer import config as config_mod
|
from steam_backlog_enforcer import config as config_mod
|
||||||
|
from steam_backlog_enforcer._flat_record import to_flat
|
||||||
from steam_backlog_enforcer._prompter import current_prompter
|
from steam_backlog_enforcer._prompter import current_prompter
|
||||||
from steam_backlog_enforcer.config import Config
|
from steam_backlog_enforcer.config import Config
|
||||||
|
|
||||||
@ -45,7 +46,7 @@ def save_credentials(api_key: str, steam_id: str) -> Config:
|
|||||||
# world-readable, nor be written to the real config during a test run.
|
# world-readable, nor be written to the real config during a test run.
|
||||||
path = config_mod.CONFIG_FILE
|
path = config_mod.CONFIG_FILE
|
||||||
on_disk = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
|
on_disk = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
|
||||||
merged = on_disk | config.__dict__
|
merged = on_disk | to_flat(config)
|
||||||
config_mod.atomic_write(path, json.dumps(merged, indent=2) + "\n")
|
config_mod.atomic_write(path, json.dumps(merged, indent=2) + "\n")
|
||||||
path.chmod(0o600)
|
path.chmod(0o600)
|
||||||
return config
|
return config
|
||||||
|
|||||||
@ -41,6 +41,7 @@ from steam_backlog_enforcer._ctl_wire import (
|
|||||||
read_line,
|
read_line,
|
||||||
socket_is_live,
|
socket_is_live,
|
||||||
)
|
)
|
||||||
|
from steam_backlog_enforcer._fail_safe import FAIL_SAFE_ERRORS
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@ -172,8 +173,8 @@ class CtlServer:
|
|||||||
line = read_line(conn)
|
line = read_line(conn)
|
||||||
if line is not None:
|
if line is not None:
|
||||||
self._write(conn, self.dispatch(line, uid))
|
self._write(conn, self.dispatch(line, uid))
|
||||||
# Catch-all on purpose: a dying connection must not kill its thread.
|
# A dying connection (timeout, hang-up) must not kill its thread.
|
||||||
except Exception: # pylint: disable=broad-exception-caught
|
except OSError:
|
||||||
logger.debug("Control connection dropped", exc_info=True)
|
logger.debug("Control connection dropped", exc_info=True)
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
@ -186,14 +187,15 @@ class CtlServer:
|
|||||||
conn.sendall(payload)
|
conn.sendall(payload)
|
||||||
|
|
||||||
def dispatch(self, line: bytes, uid: int) -> bytes:
|
def dispatch(self, line: bytes, uid: int) -> bytes:
|
||||||
"""Turn a request line into a response line. Never raises."""
|
"""Turn a request line into a response line; op failures become errors."""
|
||||||
try:
|
try:
|
||||||
return ok_response(self.run(line, uid))
|
return ok_response(self.run(line, uid))
|
||||||
except CtlError as exc:
|
except CtlError as exc:
|
||||||
logger.info("Control socket: refused (%s)", exc.code)
|
logger.info("Control socket: refused (%s)", exc.code)
|
||||||
return error_response(exc)
|
return error_response(exc)
|
||||||
# Catch-all on purpose: any op bug answers "internal error", never raises.
|
# A failing op answers "internal error"; a bug outside the tuple ends
|
||||||
except Exception: # pylint: disable=broad-exception-caught
|
# only this connection's thread (``handle`` still frees its slot).
|
||||||
|
except FAIL_SAFE_ERRORS:
|
||||||
logger.exception("Control socket op crashed")
|
logger.exception("Control socket op crashed")
|
||||||
return error_response(CtlError(OP_FAILED, "internal error"))
|
return error_response(CtlError(OP_FAILED, "internal error"))
|
||||||
|
|
||||||
|
|||||||
30
steam_backlog_enforcer/_fail_safe.py
Normal file
30
steam_backlog_enforcer/_fail_safe.py
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
"""The exceptions a fail-safe handler absorbs; anything else propagates.
|
||||||
|
|
||||||
|
No handler in the live enforcer catches ``Exception`` (kuhy's call, todo
|
||||||
|
9b9342ba). A handler that must outlive a failing input or op catches this
|
||||||
|
tuple instead:
|
||||||
|
|
||||||
|
* ``OSError``: files, sockets, ``/proc``, signals (incl. timeouts, a peer
|
||||||
|
that hung up, ``ProcessLookupError``);
|
||||||
|
* ``ValueError``: malformed data, incl. ``json`` and Unicode decode errors;
|
||||||
|
* ``TypeError`` and ``LookupError``: a payload of the wrong shape;
|
||||||
|
* ``RuntimeError``: incl. ``RecursionError``, which leisure_watch has raised;
|
||||||
|
* ``subprocess.SubprocessError``: a helper that failed or timed out.
|
||||||
|
|
||||||
|
A programming bug outside it (``AttributeError``, ``NameError``, ...) is loud:
|
||||||
|
it reaches the thread's or the process's own error reporting.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import subprocess
|
||||||
|
from typing import Final
|
||||||
|
|
||||||
|
FAIL_SAFE_ERRORS: Final[tuple[type[Exception], ...]] = (
|
||||||
|
OSError,
|
||||||
|
ValueError,
|
||||||
|
TypeError,
|
||||||
|
LookupError,
|
||||||
|
RuntimeError,
|
||||||
|
subprocess.SubprocessError,
|
||||||
|
)
|
||||||
77
steam_backlog_enforcer/_flat_record.py
Normal file
77
steam_backlog_enforcer/_flat_record.py
Normal file
@ -0,0 +1,77 @@
|
|||||||
|
"""Nested dataclass groups stored as one flat JSON object.
|
||||||
|
|
||||||
|
The persisted records (``config.json``, ``state.json``, the playtime state)
|
||||||
|
are flat JSON objects that older daemons and kuhy's hand edits rely on. In
|
||||||
|
code, related fields live in a nested dataclass, a *group*, so no record
|
||||||
|
carries more than pylint's ``max-attributes``. A group field is marked with
|
||||||
|
:func:`flat_group`; :func:`to_flat` writes its fields inline (with an
|
||||||
|
optional key prefix) at the group's position, and :func:`from_flat` reads
|
||||||
|
them back, so the bytes on disk do not change.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import fields
|
||||||
|
from typing import TYPE_CHECKING, Any, ClassVar, Final, Protocol
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Mapping
|
||||||
|
|
||||||
|
_GROUP: Final = "flat_group"
|
||||||
|
|
||||||
|
|
||||||
|
class DataclassInstance(Protocol):
|
||||||
|
"""Any dataclass instance (what ``dataclasses.fields`` accepts)."""
|
||||||
|
|
||||||
|
__dataclass_fields__: ClassVar[dict[str, Any]]
|
||||||
|
|
||||||
|
|
||||||
|
def flat_group(cls: type[DataclassInstance], prefix: str = "") -> dict[str, Any]:
|
||||||
|
"""Field metadata marking a group of *cls*, stored with key *prefix*."""
|
||||||
|
return {_GROUP: (cls, prefix)}
|
||||||
|
|
||||||
|
|
||||||
|
def _group_of(meta: Mapping[str, Any]) -> tuple[type[DataclassInstance], str] | None:
|
||||||
|
"""The group's class and key prefix, or ``None`` for a plain field."""
|
||||||
|
group: tuple[type[DataclassInstance], str] | None = meta.get(_GROUP)
|
||||||
|
return group
|
||||||
|
|
||||||
|
|
||||||
|
def to_flat(record: DataclassInstance) -> dict[str, Any]:
|
||||||
|
"""The record's fields as one flat dict, groups inlined in place."""
|
||||||
|
out: dict[str, Any] = {}
|
||||||
|
for f in fields(record):
|
||||||
|
value = getattr(record, f.name)
|
||||||
|
group = _group_of(f.metadata)
|
||||||
|
if group is None:
|
||||||
|
out[f.name] = value
|
||||||
|
else:
|
||||||
|
out.update({group[1] + k: v for k, v in to_flat(value).items()})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def flat_keys(cls: type[DataclassInstance]) -> frozenset[str]:
|
||||||
|
"""Every flat key a record of *cls* reads and writes."""
|
||||||
|
keys: set[str] = set()
|
||||||
|
for f in fields(cls):
|
||||||
|
group = _group_of(f.metadata)
|
||||||
|
if group is None:
|
||||||
|
keys.add(f.name)
|
||||||
|
else:
|
||||||
|
keys.update(group[1] + k for k in flat_keys(group[0]))
|
||||||
|
return frozenset(keys)
|
||||||
|
|
||||||
|
|
||||||
|
def from_flat[T: DataclassInstance](cls: type[T], data: Mapping[str, Any]) -> T:
|
||||||
|
"""Build *cls* from a flat dict; unknown keys are ignored."""
|
||||||
|
kwargs: dict[str, Any] = {}
|
||||||
|
for f in fields(cls):
|
||||||
|
group = _group_of(f.metadata)
|
||||||
|
if group is None:
|
||||||
|
if f.name in data:
|
||||||
|
kwargs[f.name] = data[f.name]
|
||||||
|
continue
|
||||||
|
inner, prefix = group
|
||||||
|
sub = {k: data[prefix + k] for k in flat_keys(inner) if prefix + k in data}
|
||||||
|
kwargs[f.name] = from_flat(inner, sub)
|
||||||
|
return cls(**kwargs)
|
||||||
@ -11,9 +11,11 @@ import difflib
|
|||||||
import logging
|
import logging
|
||||||
import re
|
import re
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._allowed_games import allowed_games
|
||||||
|
|
||||||
# _allowed_games, not _actions: _actions imports game_uninstall, which
|
# _allowed_games, not _actions: _actions imports game_uninstall, which
|
||||||
# imports this module. The leaf module has the same function and no cycle.
|
# imports this module. The leaf module has the same function and no cycle.
|
||||||
from steam_backlog_enforcer._allowed_games import allowed_games
|
from steam_backlog_enforcer._fail_safe import FAIL_SAFE_ERRORS
|
||||||
from steam_backlog_enforcer.config import State
|
from steam_backlog_enforcer.config import State
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@ -69,8 +71,8 @@ def _protected_name_stems() -> list[str]:
|
|||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
return [name for _, name in allowed_games(State.load()) if name]
|
return [name for _, name in allowed_games(State.load()) if name]
|
||||||
# Catch-all on purpose: a best-effort safety net, not a hard dependency.
|
# Best effort, not a hard dependency: an unreadable state protects nothing.
|
||||||
except Exception: # pylint: disable=broad-exception-caught
|
except FAIL_SAFE_ERRORS:
|
||||||
logger.exception("Could not load allowed games for the deletion safety net")
|
logger.exception("Could not load allowed games for the deletion safety net")
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
|||||||
@ -75,4 +75,4 @@ def held_shadow_today(stored: PlaytimeState | None, now: datetime) -> float:
|
|||||||
"""
|
"""
|
||||||
if stored is None or stored.day_key != gaming_day_key(now):
|
if stored is None or stored.day_key != gaming_day_key(now):
|
||||||
return 0.0
|
return 0.0
|
||||||
return stored.shadow_budget_seconds
|
return stored.shadow.budget_seconds
|
||||||
|
|||||||
@ -39,15 +39,15 @@ def apply_auth(headers: dict[str, str], auth: _AuthInfo) -> None:
|
|||||||
|
|
||||||
|
|
||||||
async def ensure_fresh_auth(ctx: _SearchCtx) -> str | None:
|
async def ensure_fresh_auth(ctx: _SearchCtx) -> str | None:
|
||||||
"""Renew ``ctx.auth`` once it is too old.
|
"""Renew ``ctx.auth.info`` once it is too old.
|
||||||
|
|
||||||
Returns ``None`` when the auth is usable, else the failure reason. A
|
Returns ``None`` when the auth is usable, else the failure reason. A
|
||||||
failed renewal trips the breaker: the stale token is never used again.
|
failed renewal trips the breaker: the stale token is never used again.
|
||||||
"""
|
"""
|
||||||
if _now() - ctx.auth_at < AUTH_MAX_AGE_S:
|
if _now() - ctx.auth.issued_at < AUTH_MAX_AGE_S:
|
||||||
return None
|
return None
|
||||||
async with ctx.auth_lock:
|
async with ctx.auth.lock:
|
||||||
if _now() - ctx.auth_at < AUTH_MAX_AGE_S:
|
if _now() - ctx.auth.issued_at < AUTH_MAX_AGE_S:
|
||||||
return None # another lookup renewed it while we waited
|
return None # another lookup renewed it while we waited
|
||||||
failures: list[str] = []
|
failures: list[str] = []
|
||||||
auth = await _get_auth_info(ctx.search_url, ctx.session, failures)
|
auth = await _get_auth_info(ctx.search_url, ctx.session, failures)
|
||||||
@ -55,8 +55,8 @@ async def ensure_fresh_auth(ctx: _SearchCtx) -> str | None:
|
|||||||
if auth is None:
|
if auth is None:
|
||||||
ctx.breaker.tripped = True
|
ctx.breaker.tripped = True
|
||||||
return f"auth refresh {failures[0] if failures else 'no token'}"
|
return f"auth refresh {failures[0] if failures else 'no token'}"
|
||||||
ctx.auth = auth
|
ctx.auth.info = auth
|
||||||
apply_auth(ctx.headers, auth)
|
apply_auth(ctx.headers, auth)
|
||||||
ctx.auth_at = _now()
|
ctx.auth.issued_at = _now()
|
||||||
logger.info("HLTB auth token refreshed.")
|
logger.info("HLTB auth token refreshed.")
|
||||||
return None
|
return None
|
||||||
|
|||||||
@ -27,7 +27,12 @@ from steam_backlog_enforcer._hltb_search_api import (
|
|||||||
_get_hltb_search_url,
|
_get_hltb_search_url,
|
||||||
forget_hltb_search_url,
|
forget_hltb_search_url,
|
||||||
)
|
)
|
||||||
from steam_backlog_enforcer._hltb_search_one import _search_one, _SearchCtx
|
from steam_backlog_enforcer._hltb_search_one import (
|
||||||
|
_AuthSlot,
|
||||||
|
_search_one,
|
||||||
|
_SearchCtx,
|
||||||
|
_SearchResults,
|
||||||
|
)
|
||||||
from steam_backlog_enforcer._hltb_types import (
|
from steam_backlog_enforcer._hltb_types import (
|
||||||
MAX_CONCURRENT,
|
MAX_CONCURRENT,
|
||||||
HLTBResult,
|
HLTBResult,
|
||||||
@ -71,7 +76,7 @@ def _check_batch(ctx: _SearchCtx) -> None:
|
|||||||
ctx.total,
|
ctx.total,
|
||||||
)
|
)
|
||||||
if ctx.breaker.tripped:
|
if ctx.breaker.tripped:
|
||||||
record_breaker(ctx.failed_ids)
|
record_breaker(ctx.results.failed_ids)
|
||||||
if failed == ctx.total:
|
if failed == ctx.total:
|
||||||
msg = f"HLTB: all {failed} lookups failed, nothing refreshed"
|
msg = f"HLTB: all {failed} lookups failed, nothing refreshed"
|
||||||
raise _fail_batch(msg)
|
raise _fail_batch(msg)
|
||||||
@ -155,9 +160,8 @@ async def _search_batch(
|
|||||||
search_url=search_url,
|
search_url=search_url,
|
||||||
headers=_search_headers(auth),
|
headers=_search_headers(auth),
|
||||||
cache=cache,
|
cache=cache,
|
||||||
polls=polls,
|
results=_SearchResults(polls=polls, extras=extras),
|
||||||
extras=extras,
|
auth=_AuthSlot(auth),
|
||||||
auth=auth,
|
|
||||||
counter={"done": 0, "found": 0, "failed": 0},
|
counter={"done": 0, "found": 0, "failed": 0},
|
||||||
total=len(games),
|
total=len(games),
|
||||||
progress_cb=progress_cb,
|
progress_cb=progress_cb,
|
||||||
|
|||||||
@ -47,6 +47,27 @@ from steam_backlog_enforcer._hltb_types import (
|
|||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class _AuthSlot:
|
||||||
|
"""The search token, when it was issued (monotonic), its renewal lock."""
|
||||||
|
|
||||||
|
info: _AuthInfo | None = None
|
||||||
|
issued_at: float = field(default_factory=time.monotonic)
|
||||||
|
lock: asyncio.Lock = field(default_factory=asyncio.Lock)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class _SearchResults:
|
||||||
|
"""What the lookups record besides hours: polls, extras and failures."""
|
||||||
|
|
||||||
|
polls: dict[int, int] = field(default_factory=dict)
|
||||||
|
extras: _HLTBExtras = field(default_factory=_HLTBExtras)
|
||||||
|
failed_ids: set[int] = field(default_factory=set)
|
||||||
|
"""Games whose lookup failed (the breaker reports them by id)."""
|
||||||
|
dirty: bool = False
|
||||||
|
"""Only flush incrementally once something was actually written."""
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class _SearchCtx:
|
class _SearchCtx:
|
||||||
"""Shared context for HLTB search requests."""
|
"""Shared context for HLTB search requests."""
|
||||||
@ -55,20 +76,12 @@ class _SearchCtx:
|
|||||||
search_url: str
|
search_url: str
|
||||||
headers: dict[str, str]
|
headers: dict[str, str]
|
||||||
cache: dict[int, float]
|
cache: dict[int, float]
|
||||||
polls: dict[int, int] = field(default_factory=dict)
|
results: _SearchResults = field(default_factory=_SearchResults)
|
||||||
extras: _HLTBExtras = field(default_factory=_HLTBExtras)
|
auth: _AuthSlot = field(default_factory=_AuthSlot)
|
||||||
auth: _AuthInfo | None = None
|
|
||||||
counter: dict[str, int] = field(default_factory=dict)
|
counter: dict[str, int] = field(default_factory=dict)
|
||||||
total: int = 0
|
total: int = 0
|
||||||
progress_cb: ProgressCb | None = None
|
progress_cb: ProgressCb | None = None
|
||||||
breaker: Breaker = field(default_factory=Breaker)
|
breaker: Breaker = field(default_factory=Breaker)
|
||||||
# When ``auth`` was issued (monotonic) and the lock for renewing it.
|
|
||||||
auth_at: float = field(default_factory=time.monotonic)
|
|
||||||
auth_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
|
|
||||||
# Games whose lookup failed (the breaker reports them by id).
|
|
||||||
failed_ids: set[int] = field(default_factory=set)
|
|
||||||
# Only flush incrementally once something was actually written.
|
|
||||||
dirty: bool = False
|
|
||||||
|
|
||||||
|
|
||||||
_Best = tuple[dict[str, Any], float]
|
_Best = tuple[dict[str, Any], float]
|
||||||
@ -107,7 +120,7 @@ async def _query_variant(
|
|||||||
Returns ``(best, None)`` on a match, ``(None, None)`` on a clean 200 with
|
Returns ``(best, None)`` on a match, ``(None, None)`` on a clean 200 with
|
||||||
no usable entry, and ``(None, reason)`` when the request itself failed.
|
no usable entry, and ``(None, reason)`` when the request itself failed.
|
||||||
"""
|
"""
|
||||||
payload = _build_search_payload(query_name, ctx.auth)
|
payload = _build_search_payload(query_name, ctx.auth.info)
|
||||||
try:
|
try:
|
||||||
async with ctx.session.post(
|
async with ctx.session.post(
|
||||||
ctx.search_url, headers=ctx.headers, data=payload
|
ctx.search_url, headers=ctx.headers, data=payload
|
||||||
@ -135,23 +148,23 @@ def _record_outcome(
|
|||||||
"""Write a match or a clean miss; a failed lookup keeps the old entry."""
|
"""Write a match or a clean miss; a failed lookup keeps the old entry."""
|
||||||
if result is not None:
|
if result is not None:
|
||||||
ctx.cache[app_id] = result.completionist_hours
|
ctx.cache[app_id] = result.completionist_hours
|
||||||
ctx.polls[app_id] = result.comp_100_count
|
ctx.results.polls[app_id] = result.comp_100_count
|
||||||
ctx.extras.count_comp[app_id] = result.count_comp
|
ctx.results.extras.count_comp[app_id] = result.count_comp
|
||||||
if result.hltb_game_id > 0:
|
if result.hltb_game_id > 0:
|
||||||
ctx.extras.hltb_game_id[app_id] = result.hltb_game_id
|
ctx.results.extras.hltb_game_id[app_id] = result.hltb_game_id
|
||||||
ctx.counter["found"] += 1
|
ctx.counter["found"] += 1
|
||||||
ctx.dirty = True
|
ctx.results.dirty = True
|
||||||
record_success()
|
record_success()
|
||||||
elif failure is not None:
|
elif failure is not None:
|
||||||
ctx.counter["failed"] += 1
|
ctx.counter["failed"] += 1
|
||||||
ctx.failed_ids.add(app_id)
|
ctx.results.failed_ids.add(app_id)
|
||||||
record_failure(failure)
|
record_failure(failure)
|
||||||
else:
|
else:
|
||||||
# Every variant answered cleanly with nothing usable: a real miss.
|
# Every variant answered cleanly with nothing usable: a real miss.
|
||||||
ctx.cache[app_id] = -1
|
ctx.cache[app_id] = -1
|
||||||
ctx.polls[app_id] = 0
|
ctx.results.polls[app_id] = 0
|
||||||
ctx.extras.count_comp[app_id] = 0
|
ctx.results.extras.count_comp[app_id] = 0
|
||||||
ctx.dirty = True
|
ctx.results.dirty = True
|
||||||
record_success()
|
record_success()
|
||||||
|
|
||||||
|
|
||||||
@ -188,8 +201,8 @@ async def _search_one(
|
|||||||
done = ctx.counter["done"]
|
done = ctx.counter["done"]
|
||||||
|
|
||||||
# Incremental save every _SAVE_INTERVAL lookups.
|
# Incremental save every _SAVE_INTERVAL lookups.
|
||||||
if ctx.dirty and not done % _SAVE_INTERVAL:
|
if ctx.results.dirty and not done % _SAVE_INTERVAL:
|
||||||
save_hltb_cache(ctx.cache, ctx.polls, ctx.extras)
|
save_hltb_cache(ctx.cache, ctx.results.polls, ctx.results.extras)
|
||||||
|
|
||||||
# Report progress.
|
# Report progress.
|
||||||
if ctx.progress_cb is not None:
|
if ctx.progress_cb is not None:
|
||||||
|
|||||||
@ -124,8 +124,8 @@ def leetcode_solved_today(config: Config) -> bool | None:
|
|||||||
can log which one happened -- and so an unreadable ledger raises an
|
can log which one happened -- and so an unreadable ledger raises an
|
||||||
incident while an honest "not solved yet" does not.
|
incident while an honest "not solved yet" does not.
|
||||||
"""
|
"""
|
||||||
url = config.leetcode_status_url
|
url = config.earn.leetcode_status_url
|
||||||
path = Path(config.leetcode_ledger_path).expanduser()
|
path = Path(config.earn.leetcode_ledger_path).expanduser()
|
||||||
# A new credit row rewrites the ledger; its stamp drops the memo at once.
|
# A new credit row rewrites the ledger; its stamp drops the memo at once.
|
||||||
stamp = file_stamp(path)
|
stamp = file_stamp(path)
|
||||||
cached = _cache.fresh(url, stamp=stamp)
|
cached = _cache.fresh(url, stamp=stamp)
|
||||||
|
|||||||
@ -34,6 +34,7 @@ import os
|
|||||||
import signal
|
import signal
|
||||||
from typing import TYPE_CHECKING, Final, Protocol
|
from typing import TYPE_CHECKING, Final, Protocol
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._fail_safe import FAIL_SAFE_ERRORS
|
||||||
from steam_backlog_enforcer._leisure_never_kill import never_kill
|
from steam_backlog_enforcer._leisure_never_kill import never_kill
|
||||||
from steam_backlog_enforcer._leisure_procs import (
|
from steam_backlog_enforcer._leisure_procs import (
|
||||||
exe_name,
|
exe_name,
|
||||||
@ -138,9 +139,8 @@ class LeisureKiller:
|
|||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
self._enforce(state, rules, verdict=verdict, stamp=stamp)
|
self._enforce(state, rules, verdict=verdict, stamp=stamp)
|
||||||
# Never raises: the enforce loop has no per-tick guard and must outlive
|
# No per-tick guard upstream: outlive a failed kill; a bug stays loud.
|
||||||
# any kill bug, so this catch-all is on purpose.
|
except FAIL_SAFE_ERRORS as exc:
|
||||||
except Exception as exc: # pylint: disable=broad-exception-caught
|
|
||||||
message = f"{type(exc).__name__}: {exc}"
|
message = f"{type(exc).__name__}: {exc}"
|
||||||
if message != self._last_error:
|
if message != self._last_error:
|
||||||
self._last_error = message
|
self._last_error = message
|
||||||
|
|||||||
@ -100,7 +100,7 @@ def abandon_manual_pick(state: State, app_id: int) -> bool:
|
|||||||
if survivor is None:
|
if survivor is None:
|
||||||
state.current_app_id = None
|
state.current_app_id = None
|
||||||
state.current_game_name = ""
|
state.current_game_name = ""
|
||||||
state.current_assigned_at = ""
|
state.assignment.current_assigned_at = ""
|
||||||
else:
|
else:
|
||||||
# The survivor has been assigned since it was picked.
|
# The survivor has been assigned since it was picked.
|
||||||
record_assignment(
|
record_assignment(
|
||||||
|
|||||||
@ -44,7 +44,7 @@ def keep_outgoing_assignment(state: State) -> dict[str, Any] | None:
|
|||||||
entry: dict[str, Any] = {
|
entry: dict[str, Any] = {
|
||||||
"app_id": app_id,
|
"app_id": app_id,
|
||||||
"game_name": state.current_game_name,
|
"game_name": state.current_game_name,
|
||||||
"started_at": state.current_assigned_at or now,
|
"started_at": state.assignment.current_assigned_at or now,
|
||||||
# Released, not active: allowed, but no lock and no pick slot.
|
# Released, not active: allowed, but no lock and no pick slot.
|
||||||
"released_at": now,
|
"released_at": now,
|
||||||
}
|
}
|
||||||
|
|||||||
@ -103,8 +103,11 @@ def playtime_tick(
|
|||||||
state = replace(
|
state = replace(
|
||||||
state,
|
state,
|
||||||
budget_seconds=max(state.budget_seconds, rules.budget_seconds),
|
budget_seconds=max(state.budget_seconds, rules.budget_seconds),
|
||||||
shadow_budget_seconds=max(
|
shadow=replace(
|
||||||
state.shadow_budget_seconds, rules.shadow_budget_seconds
|
state.shadow,
|
||||||
|
budget_seconds=max(
|
||||||
|
state.shadow.budget_seconds, rules.shadow_budget_seconds
|
||||||
|
),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@ -9,6 +9,8 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._flat_record import flat_group
|
||||||
|
|
||||||
# Unchanged by per-game attribution: `load_state` keeps only keys that are
|
# Unchanged by per-game attribution: `load_state` keeps only keys that are
|
||||||
# dataclass fields, so a record written before `per_game` existed loads with
|
# dataclass fields, so a record written before `per_game` existed loads with
|
||||||
# the field's empty default. A bump would buy nothing and would route the
|
# the field's empty default. A bump would buy nothing and would route the
|
||||||
@ -16,6 +18,39 @@ from dataclasses import dataclass, field
|
|||||||
_SCHEMA_VERSION = 1
|
_SCHEMA_VERSION = 1
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ShadowLedger:
|
||||||
|
"""Shadow leisure accounting (C4): measured, never enforced.
|
||||||
|
|
||||||
|
No :class:`PlaytimeState` field outside this group is ever written by the
|
||||||
|
shadow path, and these never feed a cutoff. Stored flat with a
|
||||||
|
``shadow_`` key prefix (``shadow_seconds``, ...).
|
||||||
|
"""
|
||||||
|
|
||||||
|
seconds: float = 0.0
|
||||||
|
"""Leisure seconds billed during ``day_key`` (wall clock, once per tick)."""
|
||||||
|
budget_seconds: float = 0.0
|
||||||
|
"""Highest ``resolve(leisure=True)`` budget of ``day_key``, in seconds."""
|
||||||
|
per_source: dict[str, float] = field(default_factory=dict)
|
||||||
|
"""Source key to shadow seconds; overlapping sources split a tick."""
|
||||||
|
paused_seconds: float = 0.0
|
||||||
|
"""Seconds a held locker grab or i3lock paused shadow billing."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class BudgetBreakdown:
|
||||||
|
"""Where one day's budget came from, resolved once per tick."""
|
||||||
|
|
||||||
|
base_seconds: float = 0.0
|
||||||
|
workout_seconds: float = 0.0
|
||||||
|
leetcode_seconds: float = 0.0
|
||||||
|
reading_seconds: float = 0.0
|
||||||
|
earned_seconds: dict[str, float] = field(default_factory=dict)
|
||||||
|
"""Seconds earned today, by earner name."""
|
||||||
|
reason: str = ""
|
||||||
|
"""One line explaining the budget in force."""
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class PlaytimeState:
|
class PlaytimeState:
|
||||||
"""Per-gaming-day playtime accounting, persisted between ticks."""
|
"""Per-gaming-day playtime accounting, persisted between ticks."""
|
||||||
@ -51,22 +86,16 @@ class PlaytimeState:
|
|||||||
|
|
||||||
What ``held_today`` holds the day at when a live re-resolution dips.
|
What ``held_today`` holds the day at when a live re-resolution dips.
|
||||||
"""
|
"""
|
||||||
# Shadow leisure accounting (C4): measured, never enforced. No field
|
shadow: ShadowLedger = field(
|
||||||
# above is ever written by the shadow path, and these never feed a cutoff.
|
default_factory=ShadowLedger, metadata=flat_group(ShadowLedger, "shadow_")
|
||||||
shadow_seconds: float = 0.0
|
)
|
||||||
"""Leisure seconds billed during ``day_key`` (wall clock, once per tick)."""
|
"""Shadow leisure accounting (C4), stored as the ``shadow_*`` keys."""
|
||||||
shadow_budget_seconds: float = 0.0
|
|
||||||
"""Highest ``resolve(leisure=True)`` budget of ``day_key``, in seconds."""
|
|
||||||
shadow_per_source: dict[str, float] = field(default_factory=dict)
|
|
||||||
"""Source key to shadow seconds; overlapping sources split a tick."""
|
|
||||||
shadow_paused_seconds: float = 0.0
|
|
||||||
"""Seconds a held locker grab or i3lock paused shadow billing."""
|
|
||||||
|
|
||||||
def is_blocked(self) -> bool:
|
def is_blocked(self) -> bool:
|
||||||
"""Whether the cutoff has engaged for this gaming day.
|
"""Whether the cutoff has engaged for this gaming day.
|
||||||
|
|
||||||
Deliberately a method rather than a field: ``save`` serialises
|
Deliberately a method rather than a field: ``save`` serialises every
|
||||||
``self.__dict__``, so a derived field would be persisted and could
|
field, so a derived field would be persisted and could
|
||||||
drift out of step with ``blocked_at``.
|
drift out of step with ``blocked_at``.
|
||||||
"""
|
"""
|
||||||
return self.blocked_at > 0.0
|
return self.blocked_at > 0.0
|
||||||
|
|||||||
@ -7,16 +7,21 @@ survive a restart mid-session.
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import dataclass, field, fields
|
from dataclasses import dataclass, field
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
from steam_backlog_enforcer._budget_resolve import resolve_budget
|
from steam_backlog_enforcer._budget_resolve import resolve_budget
|
||||||
|
from steam_backlog_enforcer._flat_record import from_flat, to_flat
|
||||||
from steam_backlog_enforcer._gaming_days import held_shadow_today, held_today
|
from steam_backlog_enforcer._gaming_days import held_shadow_today, held_today
|
||||||
from steam_backlog_enforcer._playtime_legacy import without_legacy_carry
|
from steam_backlog_enforcer._playtime_legacy import without_legacy_carry
|
||||||
from steam_backlog_enforcer._playtime_record import _SCHEMA_VERSION, PlaytimeState
|
from steam_backlog_enforcer._playtime_record import (
|
||||||
|
_SCHEMA_VERSION,
|
||||||
|
BudgetBreakdown,
|
||||||
|
PlaytimeState,
|
||||||
|
)
|
||||||
from steam_backlog_enforcer._whitelist_locking import (
|
from steam_backlog_enforcer._whitelist_locking import (
|
||||||
_try_set_immutable,
|
_try_set_immutable,
|
||||||
unlock_for_write,
|
unlock_for_write,
|
||||||
@ -26,6 +31,7 @@ from steam_backlog_enforcer.config import CONFIG_DIR, _atomic_write
|
|||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._budget_resolve import BudgetResolution
|
||||||
from steam_backlog_enforcer.config import Config
|
from steam_backlog_enforcer.config import Config
|
||||||
|
|
||||||
# Explicit because PlaytimeState now lives in _playtime_record: every existing
|
# Explicit because PlaytimeState now lives in _playtime_record: every existing
|
||||||
@ -88,13 +94,8 @@ class PlaytimeRules:
|
|||||||
count_launchers: bool
|
count_launchers: bool
|
||||||
enforcement: bool
|
enforcement: bool
|
||||||
demo: bool
|
demo: bool
|
||||||
# Today's breakdown, carried so it is resolved once; earned_seconds by name.
|
# Today's breakdown, carried so it is resolved once.
|
||||||
base_seconds: float = 0.0
|
breakdown: BudgetBreakdown = field(default_factory=BudgetBreakdown)
|
||||||
workout_seconds: float = 0.0
|
|
||||||
leetcode_seconds: float = 0.0
|
|
||||||
reading_seconds: float = 0.0
|
|
||||||
earned_seconds: dict[str, float] = field(default_factory=dict)
|
|
||||||
budget_reason: str = ""
|
|
||||||
# The shadow leisure budget (C4), held like budget_seconds; never enforced.
|
# The shadow leisure budget (C4), held like budget_seconds; never enforced.
|
||||||
shadow_budget_seconds: float = 0.0
|
shadow_budget_seconds: float = 0.0
|
||||||
# Phase 2: the billed gaming day is on the leisure budget (set per tick by
|
# Phase 2: the billed gaming day is on the leisure budget (set per tick by
|
||||||
@ -129,27 +130,30 @@ def rules_for(config: Config, *, demo: bool) -> PlaytimeRules:
|
|||||||
budget_seconds=_DEMO_BUDGET_SECONDS if resolved is None else max(live, held),
|
budget_seconds=_DEMO_BUDGET_SECONDS if resolved is None else max(live, held),
|
||||||
warn_at=_DEMO_WARN_AT if demo else _WARN_AT,
|
warn_at=_DEMO_WARN_AT if demo else _WARN_AT,
|
||||||
sigkill_after=(_DEMO_SIGKILL_AFTER_SECONDS if demo else _SIGKILL_AFTER_SECONDS),
|
sigkill_after=(_DEMO_SIGKILL_AFTER_SECONDS if demo else _SIGKILL_AFTER_SECONDS),
|
||||||
count_launchers=config.count_launcher_processes,
|
count_launchers=config.playtime.count_launcher_processes,
|
||||||
enforcement=config.playtime_enforcement,
|
enforcement=config.playtime.playtime_enforcement,
|
||||||
demo=demo,
|
demo=demo,
|
||||||
base_seconds=_DEMO_BUDGET_SECONDS
|
breakdown=_breakdown(resolved, held_note if held > live else ""),
|
||||||
if resolved is None
|
|
||||||
else resolved.base_seconds,
|
|
||||||
workout_seconds=0.0 if resolved is None else resolved.workout_seconds,
|
|
||||||
leetcode_seconds=0.0 if resolved is None else resolved.leetcode_seconds,
|
|
||||||
reading_seconds=0.0 if resolved is None else resolved.reading_seconds,
|
|
||||||
earned_seconds={} if resolved is None else dict(resolved.earned_seconds),
|
|
||||||
budget_reason=(
|
|
||||||
"demo run"
|
|
||||||
if resolved is None
|
|
||||||
else resolved.reason + (held_note if held > live else "")
|
|
||||||
),
|
|
||||||
shadow_budget_seconds=0.0
|
shadow_budget_seconds=0.0
|
||||||
if resolved is None
|
if resolved is None
|
||||||
else max(resolved.shadow_seconds, held_shadow_today(stored, now)),
|
else max(resolved.shadow_seconds, held_shadow_today(stored, now)),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _breakdown(resolved: BudgetResolution | None, held_note: str) -> BudgetBreakdown:
|
||||||
|
"""The breakdown of *resolved*, or the demo run's when it is ``None``."""
|
||||||
|
if resolved is None:
|
||||||
|
return BudgetBreakdown(base_seconds=_DEMO_BUDGET_SECONDS, reason="demo run")
|
||||||
|
return BudgetBreakdown(
|
||||||
|
base_seconds=resolved.base_seconds,
|
||||||
|
workout_seconds=resolved.workout_seconds,
|
||||||
|
leetcode_seconds=resolved.leetcode_seconds,
|
||||||
|
reading_seconds=resolved.reading_seconds,
|
||||||
|
earned_seconds=dict(resolved.earned_seconds),
|
||||||
|
reason=resolved.reason + held_note,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def state_path(*, demo: bool) -> Path:
|
def state_path(*, demo: bool) -> Path:
|
||||||
"""Return the state file for a demo or production run.
|
"""Return the state file for a demo or production run.
|
||||||
|
|
||||||
@ -190,8 +194,7 @@ def load_state(*, demo: bool) -> PlaytimeState | None:
|
|||||||
if not isinstance(data, dict) or data.get("schema_version") != _SCHEMA_VERSION:
|
if not isinstance(data, dict) or data.get("schema_version") != _SCHEMA_VERSION:
|
||||||
logger.warning("Playtime state at %s has an unknown schema.", path)
|
logger.warning("Playtime state at %s has an unknown schema.", path)
|
||||||
return None
|
return None
|
||||||
known = {f.name for f in fields(PlaytimeState)}
|
state = from_flat(PlaytimeState, data)
|
||||||
state = PlaytimeState(**{k: v for k, v in data.items() if k in known})
|
|
||||||
return without_legacy_carry(state, data.get("carry"))
|
return without_legacy_carry(state, data.get("carry"))
|
||||||
|
|
||||||
|
|
||||||
@ -210,6 +213,6 @@ def save_state(state: PlaytimeState, *, demo: bool) -> None:
|
|||||||
path = state_path(demo=demo)
|
path = state_path(demo=demo)
|
||||||
if not demo:
|
if not demo:
|
||||||
unlock_for_write(path)
|
unlock_for_write(path)
|
||||||
_atomic_write(path, json.dumps(state.__dict__, indent=2) + "\n", mode=STATE_MODE)
|
_atomic_write(path, json.dumps(to_flat(state), indent=2) + "\n", mode=STATE_MODE)
|
||||||
if not demo:
|
if not demo:
|
||||||
_try_set_immutable(path, immutable=True)
|
_try_set_immutable(path, immutable=True)
|
||||||
|
|||||||
@ -59,7 +59,7 @@ def read_ledger_read_today(path: Path) -> bool | None:
|
|||||||
|
|
||||||
def read_today(config: Config) -> bool | None:
|
def read_today(config: Config) -> bool | None:
|
||||||
"""Today's reading answer, memoised like the other earners."""
|
"""Today's reading answer, memoised like the other earners."""
|
||||||
path = Path(config.book_ledger_path).expanduser()
|
path = Path(config.earn.book_ledger_path).expanduser()
|
||||||
# Stat before reading, so a credit landing mid-read is re-read next tick.
|
# Stat before reading, so a credit landing mid-read is re-read next tick.
|
||||||
stamp = file_stamp(path)
|
stamp = file_stamp(path)
|
||||||
cached = _cache.fresh(_CACHE_KEY, stamp=stamp)
|
cached = _cache.fresh(_CACHE_KEY, stamp=stamp)
|
||||||
|
|||||||
@ -88,7 +88,7 @@ def _unexpected_unlocks(
|
|||||||
Tuple of (name, app_id, diff) if tampering detected, else None.
|
Tuple of (name, app_id, diff) if tampering detected, else None.
|
||||||
"""
|
"""
|
||||||
app_id = entry["app_id"]
|
app_id = entry["app_id"]
|
||||||
released = iso_to_epoch(state.released_at.get(str(app_id), ""))
|
released = iso_to_epoch(state.assignment.released_at.get(str(app_id), ""))
|
||||||
if released is not None:
|
if released is not None:
|
||||||
# Released below 100%: the snapshot predates the unlocks earned while
|
# Released below 100%: the snapshot predates the unlocks earned while
|
||||||
# it was assigned, so only unlocks after the release are suspicious.
|
# it was assigned, so only unlocks after the release are suspicious.
|
||||||
|
|||||||
@ -32,6 +32,7 @@ from typing import TYPE_CHECKING, Final
|
|||||||
from leisure_watch.facts import read_now
|
from leisure_watch.facts import read_now
|
||||||
from leisure_watch.lockstate import paused_by
|
from leisure_watch.lockstate import paused_by
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._fail_safe import FAIL_SAFE_ERRORS
|
||||||
from steam_backlog_enforcer._playtime_state import _DELTA_CLAMP_FACTOR
|
from steam_backlog_enforcer._playtime_state import _DELTA_CLAMP_FACTOR
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
@ -120,8 +121,8 @@ def observe_shadow(owners: dict[int, str], *, stamp: float) -> ShadowVerdict:
|
|||||||
if paused is not None:
|
if paused is not None:
|
||||||
return ShadowVerdict(paused_by=paused, keys=())
|
return ShadowVerdict(paused_by=paused, keys=())
|
||||||
fact = read_now(NOW_PATH, stamp, max_age=_MAX_AGE_SECONDS)
|
fact = read_now(NOW_PATH, stamp, max_age=_MAX_AGE_SECONDS)
|
||||||
# Catch-all on purpose: the loop must outlive any shadow input bug.
|
# The loop must outlive any unreadable shadow input; a bug stays loud.
|
||||||
except Exception as exc: # pylint: disable=broad-exception-caught
|
except FAIL_SAFE_ERRORS as exc:
|
||||||
if _should_warn(exc):
|
if _should_warn(exc):
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"Shadow inputs unreadable (%r); failing closed.", exc, exc_info=True
|
"Shadow inputs unreadable (%r); failing closed.", exc, exc_info=True
|
||||||
@ -172,16 +173,19 @@ def shadow_accumulate(
|
|||||||
return state
|
return state
|
||||||
credited = min(delta, interval * _DELTA_CLAMP_FACTOR)
|
credited = min(delta, interval * _DELTA_CLAMP_FACTOR)
|
||||||
if verdict.paused_by is not None:
|
if verdict.paused_by is not None:
|
||||||
paused = state.shadow_paused_seconds + credited
|
paused = state.shadow.paused_seconds + credited
|
||||||
return replace(state, shadow_paused_seconds=paused)
|
return replace(state, shadow=replace(state.shadow, paused_seconds=paused))
|
||||||
if not verdict.keys:
|
if not verdict.keys:
|
||||||
return state
|
return state
|
||||||
share = credited / len(verdict.keys)
|
share = credited / len(verdict.keys)
|
||||||
per_source = dict(state.shadow_per_source)
|
per_source = dict(state.shadow.per_source)
|
||||||
for key in verdict.keys:
|
for key in verdict.keys:
|
||||||
per_source[key] = per_source.get(key, 0.0) + share
|
per_source[key] = per_source.get(key, 0.0) + share
|
||||||
return replace(
|
return replace(
|
||||||
state,
|
state,
|
||||||
shadow_seconds=state.shadow_seconds + credited,
|
shadow=replace(
|
||||||
shadow_per_source=per_source,
|
state.shadow,
|
||||||
|
seconds=state.shadow.seconds + credited,
|
||||||
|
per_source=per_source,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
@ -41,18 +41,18 @@ class ShadowJournal:
|
|||||||
if verdict == self._last:
|
if verdict == self._last:
|
||||||
return
|
return
|
||||||
self._last = verdict
|
self._last = verdict
|
||||||
remaining = state.shadow_budget_seconds - state.shadow_seconds
|
remaining = state.shadow.budget_seconds - state.shadow.seconds
|
||||||
self._log.record(
|
self._log.record(
|
||||||
EVENT_SHADOW_CHANGE,
|
EVENT_SHADOW_CHANGE,
|
||||||
shadow_state=verdict.state,
|
shadow_state=verdict.state,
|
||||||
paused_by=verdict.paused_by,
|
paused_by=verdict.paused_by,
|
||||||
sources=list(verdict.keys),
|
sources=list(verdict.keys),
|
||||||
day_key=state.day_key,
|
day_key=state.day_key,
|
||||||
shadow_seconds=round(state.shadow_seconds, 3),
|
shadow_seconds=round(state.shadow.seconds, 3),
|
||||||
shadow_budget_seconds=round(state.shadow_budget_seconds, 3),
|
shadow_budget_seconds=round(state.shadow.budget_seconds, 3),
|
||||||
shadow_remaining_seconds=round(remaining, 3),
|
shadow_remaining_seconds=round(remaining, 3),
|
||||||
shadow_paused_seconds=round(state.shadow_paused_seconds, 3),
|
shadow_paused_seconds=round(state.shadow.paused_seconds, 3),
|
||||||
shadow_per_source={
|
shadow_per_source={
|
||||||
k: round(v, 3) for k, v in state.shadow_per_source.items()
|
k: round(v, 3) for k, v in state.shadow.per_source.items()
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|||||||
@ -22,12 +22,12 @@ def shadow_view(state: PlaytimeState) -> dict[str, Any]:
|
|||||||
Used/budget/remaining seconds, whether the leisure budget would block
|
Used/budget/remaining seconds, whether the leisure budget would block
|
||||||
now, paused seconds, and the per-source split.
|
now, paused seconds, and the per-source split.
|
||||||
"""
|
"""
|
||||||
remaining = max(0.0, state.shadow_budget_seconds - state.shadow_seconds)
|
remaining = max(0.0, state.shadow.budget_seconds - state.shadow.seconds)
|
||||||
return {
|
return {
|
||||||
"seconds_used": round(state.shadow_seconds, 1),
|
"seconds_used": round(state.shadow.seconds, 1),
|
||||||
"budget_seconds": state.shadow_budget_seconds,
|
"budget_seconds": state.shadow.budget_seconds,
|
||||||
"seconds_remaining": round(remaining, 1),
|
"seconds_remaining": round(remaining, 1),
|
||||||
"would_block": remaining <= 0.0,
|
"would_block": remaining <= 0.0,
|
||||||
"paused_seconds": round(state.shadow_paused_seconds, 1),
|
"paused_seconds": round(state.shadow.paused_seconds, 1),
|
||||||
"per_source": {k: round(v, 1) for k, v in state.shadow_per_source.items()},
|
"per_source": {k: round(v, 1) for k, v in state.shadow.per_source.items()},
|
||||||
}
|
}
|
||||||
|
|||||||
@ -27,18 +27,18 @@ def migrate_legacy_manual_pick(state: State) -> bool:
|
|||||||
Returns:
|
Returns:
|
||||||
Whether a legacy pick was migrated.
|
Whether a legacy pick was migrated.
|
||||||
"""
|
"""
|
||||||
if state.manual_pick_app_id is None or state.manual_picks:
|
if state.legacy_pick.app_id is None or state.manual_picks:
|
||||||
return False
|
return False
|
||||||
state.manual_picks = [
|
state.manual_picks = [
|
||||||
{
|
{
|
||||||
"app_id": state.manual_pick_app_id,
|
"app_id": state.legacy_pick.app_id,
|
||||||
"game_name": state.manual_pick_game_name,
|
"game_name": state.legacy_pick.game_name,
|
||||||
"started_at": state.manual_pick_started_at,
|
"started_at": state.legacy_pick.started_at,
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
state.manual_pick_app_id = None
|
state.legacy_pick.app_id = None
|
||||||
state.manual_pick_game_name = ""
|
state.legacy_pick.game_name = ""
|
||||||
state.manual_pick_started_at = ""
|
state.legacy_pick.started_at = ""
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
@ -67,18 +67,20 @@ def backfill_assignment_times(state: State) -> bool:
|
|||||||
changed |= _stamp_if_missing(state, app_id, started_at)
|
changed |= _stamp_if_missing(state, app_id, started_at)
|
||||||
current = state.current_app_id
|
current = state.current_app_id
|
||||||
if current is not None:
|
if current is not None:
|
||||||
if not state.current_assigned_at:
|
if not state.assignment.current_assigned_at:
|
||||||
# A current game that is also a pick was assigned when picked.
|
# A current game that is also a pick was assigned when picked.
|
||||||
state.current_assigned_at = pick_started.get(current) or (
|
state.assignment.current_assigned_at = pick_started.get(current) or (
|
||||||
datetime.now(UTC).isoformat()
|
datetime.now(UTC).isoformat()
|
||||||
)
|
)
|
||||||
changed = True
|
changed = True
|
||||||
changed |= _stamp_if_missing(state, current, state.current_assigned_at)
|
changed |= _stamp_if_missing(
|
||||||
|
state, current, state.assignment.current_assigned_at
|
||||||
|
)
|
||||||
return changed
|
return changed
|
||||||
|
|
||||||
|
|
||||||
def _stamp_if_missing(state: State, app_id: int, stamp: str) -> bool:
|
def _stamp_if_missing(state: State, app_id: int, stamp: str) -> bool:
|
||||||
if str(app_id) in state.last_assigned_at:
|
if str(app_id) in state.assignment.last_assigned_at:
|
||||||
return False
|
return False
|
||||||
state.last_assigned_at[str(app_id)] = stamp
|
state.assignment.last_assigned_at[str(app_id)] = stamp
|
||||||
return True
|
return True
|
||||||
|
|||||||
@ -41,6 +41,7 @@ from datetime import UTC, datetime
|
|||||||
from typing import TYPE_CHECKING, Any
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
from steam_backlog_enforcer._actions import allowed_app_ids
|
from steam_backlog_enforcer._actions import allowed_app_ids
|
||||||
|
from steam_backlog_enforcer._flat_record import to_flat
|
||||||
from steam_backlog_enforcer._hltb_types import _read_raw_cache
|
from steam_backlog_enforcer._hltb_types import _read_raw_cache
|
||||||
from steam_backlog_enforcer._scanning_confidence import (
|
from steam_backlog_enforcer._scanning_confidence import (
|
||||||
_MIN_COMP_100_POLLS,
|
_MIN_COMP_100_POLLS,
|
||||||
@ -177,5 +178,7 @@ def build_web_dataset(state: State) -> WebDataset:
|
|||||||
|
|
||||||
|
|
||||||
def dataset_to_payload(dataset: WebDataset) -> dict[str, Any]:
|
def dataset_to_payload(dataset: WebDataset) -> dict[str, Any]:
|
||||||
"""Serialize a ``WebDataset`` to a JSON-ready dict."""
|
"""Serialize a ``WebDataset`` to a JSON-ready dict; game rows stay flat."""
|
||||||
return asdict(dataset)
|
payload = asdict(dataset)
|
||||||
|
payload["games"] = [to_flat(game) for game in dataset.games]
|
||||||
|
return payload
|
||||||
|
|||||||
@ -14,7 +14,7 @@ from steam_backlog_enforcer._scanning_confidence import (
|
|||||||
_MIN_CONFIDENCE_SUM,
|
_MIN_CONFIDENCE_SUM,
|
||||||
_MIN_COUNT_COMP,
|
_MIN_COUNT_COMP,
|
||||||
)
|
)
|
||||||
from steam_backlog_enforcer._web_models import DefaultSummary, WebGame
|
from steam_backlog_enforcer._web_models import DefaultSummary, WebGame, WebHltb
|
||||||
from steam_backlog_enforcer.protondb import (
|
from steam_backlog_enforcer.protondb import (
|
||||||
ProtonDBRating,
|
ProtonDBRating,
|
||||||
_load_cache,
|
_load_cache,
|
||||||
@ -38,16 +38,17 @@ def _worst_hours(game: GameInfo, cache_hours: float, leisure: float) -> float:
|
|||||||
|
|
||||||
def _passes_default_confidence(game: WebGame) -> bool:
|
def _passes_default_confidence(game: WebGame) -> bool:
|
||||||
"""True if the game clears all three CLI HLTB-confidence thresholds."""
|
"""True if the game clears all three CLI HLTB-confidence thresholds."""
|
||||||
if game.comp_100_count < _MIN_COMP_100_POLLS:
|
if game.hltb.comp_100_count < _MIN_COMP_100_POLLS:
|
||||||
return False
|
return False
|
||||||
if game.count_comp < _MIN_COUNT_COMP:
|
if game.hltb.count_comp < _MIN_COUNT_COMP:
|
||||||
return False
|
return False
|
||||||
return game.comp_100_count + game.count_comp >= _MIN_CONFIDENCE_SUM
|
return game.hltb.comp_100_count + game.hltb.count_comp >= _MIN_CONFIDENCE_SUM
|
||||||
|
|
||||||
|
|
||||||
def _has_any_time(game: WebGame) -> bool:
|
def _has_any_time(game: WebGame) -> bool:
|
||||||
"""True if the game has at least one positive time estimate."""
|
"""True if the game has at least one positive time estimate."""
|
||||||
return game.worst_hours > 0 or game.rush_hours > 0 or game.leisure_hours > 0
|
hltb = game.hltb
|
||||||
|
return hltb.worst_hours > 0 or hltb.rush_hours > 0 or hltb.leisure_hours > 0
|
||||||
|
|
||||||
|
|
||||||
def _build_games(games: list[GameInfo], exclude: set[int]) -> list[WebGame]:
|
def _build_games(games: list[GameInfo], exclude: set[int]) -> list[WebGame]:
|
||||||
@ -80,12 +81,14 @@ def _build_games(games: list[GameInfo], exclude: set[int]) -> list[WebGame]:
|
|||||||
name=game.name,
|
name=game.name,
|
||||||
completion_pct=round(game.completion_pct, 1),
|
completion_pct=round(game.completion_pct, 1),
|
||||||
playtime_minutes=game.playtime_minutes,
|
playtime_minutes=game.playtime_minutes,
|
||||||
rush_hours=rush,
|
hltb=WebHltb(
|
||||||
leisure_hours=leisure,
|
rush_hours=rush,
|
||||||
worst_hours=_worst_hours(game, cache_hours, leisure),
|
leisure_hours=leisure,
|
||||||
count_comp=count_comp,
|
worst_hours=_worst_hours(game, cache_hours, leisure),
|
||||||
comp_100_count=comp_100_count,
|
count_comp=count_comp,
|
||||||
hltb_game_id=hltb_game_id,
|
comp_100_count=comp_100_count,
|
||||||
|
hltb_game_id=hltb_game_id,
|
||||||
|
),
|
||||||
protondb_tier=rating.tier,
|
protondb_tier=rating.tier,
|
||||||
protondb_trending_tier=rating.trending_tier,
|
protondb_trending_tier=rating.trending_tier,
|
||||||
protondb_score=rating.score,
|
protondb_score=rating.score,
|
||||||
@ -115,7 +118,7 @@ def _default_qualifying(rows: list[WebGame]) -> list[WebGame]:
|
|||||||
|
|
||||||
def _sum_positive(rows: list[WebGame], attr: str) -> float:
|
def _sum_positive(rows: list[WebGame], attr: str) -> float:
|
||||||
"""Sum a positive-only hour attribute across rows (matches ``_sum_hours``)."""
|
"""Sum a positive-only hour attribute across rows (matches ``_sum_hours``)."""
|
||||||
total = sum(getattr(g, attr) for g in rows if getattr(g, attr) > 0)
|
total = sum(getattr(g.hltb, attr) for g in rows if getattr(g.hltb, attr) > 0)
|
||||||
return round(total, 1)
|
return round(total, 1)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -8,28 +8,41 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._flat_record import flat_group
|
||||||
|
|
||||||
# Mirrors ``_stats._HOURS_PER_DAY_PRESETS`` but mutable/JSON-friendly.
|
# Mirrors ``_stats._HOURS_PER_DAY_PRESETS`` but mutable/JSON-friendly.
|
||||||
HOURS_PER_DAY_PRESETS = [2.0, 4.0, 6.0, 8.0]
|
HOURS_PER_DAY_PRESETS = [2.0, 4.0, 6.0, 8.0]
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class WebGame:
|
class WebHltb:
|
||||||
"""One incomplete candidate game, with raw filterable fields.
|
"""A game's HLTB times and poll counts, as one :class:`WebGame` group.
|
||||||
|
|
||||||
Hour fields use ``-1`` to mean "no data" (matching the cache convention),
|
Hour fields use ``-1`` to mean "no data" (matching the cache convention),
|
||||||
so the client can choose to include or exclude unknown-length games.
|
so the client can choose to include or exclude unknown-length games.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
app_id: int
|
|
||||||
name: str
|
|
||||||
completion_pct: float
|
|
||||||
playtime_minutes: int
|
|
||||||
rush_hours: float
|
rush_hours: float
|
||||||
leisure_hours: float
|
leisure_hours: float
|
||||||
worst_hours: float
|
worst_hours: float
|
||||||
count_comp: int
|
count_comp: int
|
||||||
comp_100_count: int
|
comp_100_count: int
|
||||||
hltb_game_id: int
|
hltb_game_id: int
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class WebGame:
|
||||||
|
"""One incomplete candidate game, with raw filterable fields.
|
||||||
|
|
||||||
|
Served flat: :func:`~_flat_record.to_flat` inlines ``hltb`` so the browser
|
||||||
|
sees ``rush_hours`` etc. beside ``app_id``.
|
||||||
|
"""
|
||||||
|
|
||||||
|
app_id: int
|
||||||
|
name: str
|
||||||
|
completion_pct: float
|
||||||
|
playtime_minutes: int
|
||||||
|
hltb: WebHltb = field(metadata=flat_group(WebHltb))
|
||||||
protondb_tier: str
|
protondb_tier: str
|
||||||
protondb_trending_tier: str
|
protondb_trending_tier: str
|
||||||
protondb_score: float
|
protondb_score: float
|
||||||
|
|||||||
@ -22,6 +22,7 @@ from pathlib import Path
|
|||||||
from urllib.parse import parse_qs, urlsplit
|
from urllib.parse import parse_qs, urlsplit
|
||||||
|
|
||||||
from steam_backlog_enforcer import _web_auth, _web_process
|
from steam_backlog_enforcer import _web_auth, _web_process
|
||||||
|
from steam_backlog_enforcer._fail_safe import FAIL_SAFE_ERRORS
|
||||||
from steam_backlog_enforcer._serve_stale import outdated_source
|
from steam_backlog_enforcer._serve_stale import outdated_source
|
||||||
from steam_backlog_enforcer._web_errors import ApiError, not_found
|
from steam_backlog_enforcer._web_errors import ApiError, not_found
|
||||||
from steam_backlog_enforcer._web_io import (
|
from steam_backlog_enforcer._web_io import (
|
||||||
@ -101,8 +102,9 @@ class _Handler(BaseHTTPRequestHandler):
|
|||||||
self._dispatch(method, split.path, _query(split.query))
|
self._dispatch(method, split.path, _query(split.query))
|
||||||
except ApiError as exc:
|
except ApiError as exc:
|
||||||
send_error(self, exc)
|
send_error(self, exc)
|
||||||
# Catch-all on purpose: any bug answers 500, the server keeps serving.
|
# A failing route answers 500 and the server keeps serving; a bug
|
||||||
except Exception: # pylint: disable=broad-exception-caught
|
# outside the tuple goes to http.server's own error report.
|
||||||
|
except FAIL_SAFE_ERRORS:
|
||||||
logger.exception("%s %s failed", method, split.path)
|
logger.exception("%s %s failed", method, split.path)
|
||||||
msg = "The server failed to answer this request; see its log."
|
msg = "The server failed to answer this request; see its log."
|
||||||
send_error(
|
send_error(
|
||||||
|
|||||||
@ -36,7 +36,7 @@ def reset_cache() -> None:
|
|||||||
|
|
||||||
def workout_log_path(config: Config) -> Path:
|
def workout_log_path(config: Config) -> Path:
|
||||||
"""screen-locker's ``log.json``, which ``gaming.workout_today`` derives from."""
|
"""screen-locker's ``log.json``, which ``gaming.workout_today`` derives from."""
|
||||||
return Path(config.workout_log_path).expanduser()
|
return Path(config.earn.workout_log_path).expanduser()
|
||||||
|
|
||||||
|
|
||||||
def _fetch_workout_today(url: str) -> bool:
|
def _fetch_workout_today(url: str) -> bool:
|
||||||
@ -67,7 +67,7 @@ def workout_logged_today(config: Config) -> bool | None:
|
|||||||
reached or its answer could not be understood. ``None`` is deliberately
|
reached or its answer could not be understood. ``None`` is deliberately
|
||||||
distinct from ``False`` so the caller can log which one happened.
|
distinct from ``False`` so the caller can log which one happened.
|
||||||
"""
|
"""
|
||||||
url = config.workout_status_url
|
url = config.earn.workout_status_url
|
||||||
# Stat before asking: a credited workout rewrites log.json, and the new
|
# Stat before asking: a credited workout rewrites log.json, and the new
|
||||||
# stamp re-asks on the very next tick instead of after the cache TTL.
|
# stamp re-asks on the very next tick instead of after the cache TTL.
|
||||||
stamp = file_stamp(workout_log_path(config))
|
stamp = file_stamp(workout_log_path(config))
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import contextlib
|
import contextlib
|
||||||
from dataclasses import dataclass, field, fields
|
from dataclasses import dataclass, field
|
||||||
from datetime import UTC, datetime, timedelta
|
from datetime import UTC, datetime, timedelta
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
@ -12,6 +12,13 @@ from pathlib import Path
|
|||||||
import tempfile
|
import tempfile
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._config_groups import (
|
||||||
|
AssignmentTimes,
|
||||||
|
EarnSources,
|
||||||
|
LegacyManualPick,
|
||||||
|
PlaytimePolicy,
|
||||||
|
)
|
||||||
|
from steam_backlog_enforcer._flat_record import flat_group, from_flat, to_flat
|
||||||
from steam_backlog_enforcer._state_migrations import (
|
from steam_backlog_enforcer._state_migrations import (
|
||||||
backfill_assignment_times,
|
backfill_assignment_times,
|
||||||
migrate_legacy_manual_pick,
|
migrate_legacy_manual_pick,
|
||||||
@ -76,11 +83,6 @@ def _atomic_write(path: Path, data: str, *, mode: int | None = None) -> None:
|
|||||||
atomic_write = _atomic_write
|
atomic_write = _atomic_write
|
||||||
|
|
||||||
|
|
||||||
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
|
@dataclass
|
||||||
class Config:
|
class Config:
|
||||||
"""User configuration."""
|
"""User configuration."""
|
||||||
@ -97,48 +99,18 @@ class Config:
|
|||||||
All active picks stay installed and visible; the enforcer treats them as
|
All active picks stay installed and visible; the enforcer treats them as
|
||||||
one allowed set. Raising this weakens enforcement proportionally.
|
one allowed set. Raising this weakens enforcement proportionally.
|
||||||
"""
|
"""
|
||||||
book_ledger_path: str = "~/.local/share/book_guard/ledger.json"
|
earn: EarnSources = field(
|
||||||
"""book-guard's signed ledger: the reading hour's only transport."""
|
default_factory=EarnSources, metadata=flat_group(EarnSources)
|
||||||
workout_status_url: str = "http://127.0.0.1:8770/api/status"
|
)
|
||||||
"""Where to ask whether today has a counted workout. Loopback only."""
|
playtime: PlaytimePolicy = field(
|
||||||
workout_log_path: str = "~/src/screen-locker/screen_locker/log.json"
|
default_factory=PlaytimePolicy, metadata=flat_group(PlaytimePolicy)
|
||||||
"""screen-locker's log.json; a change re-asks that URL at once."""
|
)
|
||||||
leetcode_ledger_path: str = "~/.local/share/leetcode_guard/ledger.json"
|
|
||||||
leetcode_status_url: str = "http://127.0.0.1:8771/api/status"
|
|
||||||
"""LeetCode's transports: ledger first, this loopback URL as fallback."""
|
|
||||||
count_launcher_processes: bool = True
|
|
||||||
"""Whether time spent in non-Steam launchers counts against the budget.
|
|
||||||
|
|
||||||
Set False if a launcher legitimately idles in the tray all day. Leaving it
|
|
||||||
True is the safer default: under-counting is the failure mode that quietly
|
|
||||||
defeats the budget entirely.
|
|
||||||
"""
|
|
||||||
counted_processes: list[dict[str, Any]] | None = None
|
|
||||||
"""Non-Steam games that count against the budget, beyond the launcher set.
|
|
||||||
|
|
||||||
Each entry is ``{"id": ..., "label": ..., "names": [...]}``. ``None`` means
|
|
||||||
"use the built-in defaults" (osu!lazer); an explicit ``[]`` means "none",
|
|
||||||
which is why this is not simply an empty list. Parsed and validated by
|
|
||||||
``leisure_watch.procscan`` (once ``_counted_procs``) — the field exists
|
|
||||||
here only so that ``save()`` round-trips a hand-edited list instead of
|
|
||||||
dropping it.
|
|
||||||
|
|
||||||
Deliberately separate from ``LAUNCHER_PROCESS_NAMES``: that frozenset is
|
|
||||||
also the total-block kill list, so adding a game there has side effects
|
|
||||||
this list does not.
|
|
||||||
"""
|
|
||||||
playtime_enforcement: bool = True
|
|
||||||
"""Master switch for the daily gaming budget.
|
|
||||||
|
|
||||||
Disabling stops the cutoff but never strands a live block — the release
|
|
||||||
path runs regardless, so "disabled" cannot come to mean "blocked forever".
|
|
||||||
"""
|
|
||||||
|
|
||||||
def save(self) -> None:
|
def save(self) -> None:
|
||||||
"""Persist config to disk."""
|
"""Persist config to disk."""
|
||||||
_atomic_write(
|
_atomic_write(
|
||||||
CONFIG_FILE,
|
CONFIG_FILE,
|
||||||
json.dumps(self.__dict__, indent=2) + "\n",
|
json.dumps(to_flat(self), indent=2) + "\n",
|
||||||
)
|
)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@ -146,7 +118,7 @@ class Config:
|
|||||||
"""Load config from disk, or return defaults."""
|
"""Load config from disk, or return defaults."""
|
||||||
if CONFIG_FILE.exists():
|
if CONFIG_FILE.exists():
|
||||||
data = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
data = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
||||||
return cls(**{k: v for k, v in data.items() if k in _field_names(cls)})
|
return from_flat(cls, data)
|
||||||
return cls()
|
return cls()
|
||||||
|
|
||||||
|
|
||||||
@ -166,27 +138,20 @@ class State:
|
|||||||
"""
|
"""
|
||||||
enforcement_started_at: str = ""
|
enforcement_started_at: str = ""
|
||||||
"""ISO-8601 UTC timestamp set on the first game assignment."""
|
"""ISO-8601 UTC timestamp set on the first game assignment."""
|
||||||
manual_pick_app_id: int | None = None
|
legacy_pick: LegacyManualPick = field(
|
||||||
manual_pick_game_name: str = ""
|
default_factory=LegacyManualPick,
|
||||||
manual_pick_started_at: str = ""
|
metadata=flat_group(LegacyManualPick, "manual_pick_"),
|
||||||
"""Legacy single-slot manual pick, migrated into ``manual_picks`` on load.
|
)
|
||||||
|
|
||||||
Kept as fields so an older ``state.json`` still deserialises; they are
|
|
||||||
blanked once migrated and are never written again.
|
|
||||||
"""
|
|
||||||
manual_picks: list[dict[str, Any]] = field(default_factory=list)
|
manual_picks: list[dict[str, Any]] = field(default_factory=list)
|
||||||
"""Manual picks, newest last; inactive ones stay until a new choice.
|
"""Manual picks, newest last; inactive ones stay until a new choice.
|
||||||
|
|
||||||
Each entry is ``{"app_id": int, "game_name": str, "started_at": iso}``,
|
Each entry is ``{"app_id": int, "game_name": str, "started_at": iso}``,
|
||||||
plus ``"released_at": iso`` once it earned a new achievement. Plain dicts
|
plus ``"released_at": iso`` once it earned a new achievement. Plain dicts
|
||||||
because ``save`` serialises ``self.__dict__`` straight to JSON.
|
because ``save`` serialises them straight to JSON.
|
||||||
"""
|
"""
|
||||||
current_assigned_at: str = ""
|
assignment: AssignmentTimes = field(
|
||||||
"""ISO time the current game was assigned; unlocks after it release it."""
|
default_factory=AssignmentTimes, metadata=flat_group(AssignmentTimes)
|
||||||
last_assigned_at: dict[str, str] = field(default_factory=dict)
|
)
|
||||||
"""``str(app_id)`` → ISO time of its latest assignment (pick ordering)."""
|
|
||||||
released_at: dict[str, str] = field(default_factory=dict)
|
|
||||||
"""``str(app_id)`` → ISO time it was released below 100% (tampering)."""
|
|
||||||
store_unblocked_until: str = ""
|
store_unblocked_until: str = ""
|
||||||
"""ISO deadline of the open store window (``unblock``); CLI-written only."""
|
"""ISO deadline of the open store window (``unblock``); CLI-written only."""
|
||||||
|
|
||||||
@ -222,7 +187,7 @@ class State:
|
|||||||
"""Persist state to disk."""
|
"""Persist state to disk."""
|
||||||
_atomic_write(
|
_atomic_write(
|
||||||
STATE_FILE,
|
STATE_FILE,
|
||||||
json.dumps(self.__dict__, indent=2) + "\n",
|
json.dumps(to_flat(self), indent=2) + "\n",
|
||||||
)
|
)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@ -234,7 +199,7 @@ class State:
|
|||||||
except json.JSONDecodeError, OSError, ValueError:
|
except json.JSONDecodeError, OSError, ValueError:
|
||||||
logger.warning("Corrupt state file, using defaults.")
|
logger.warning("Corrupt state file, using defaults.")
|
||||||
return cls()
|
return cls()
|
||||||
state = cls(**{k: v for k, v in data.items() if k in _field_names(cls)})
|
state = from_flat(cls, data)
|
||||||
migrated = migrate_legacy_manual_pick(state)
|
migrated = migrate_legacy_manual_pick(state)
|
||||||
if backfill_assignment_times(state) or migrated:
|
if backfill_assignment_times(state) or migrated:
|
||||||
state.save()
|
state.save()
|
||||||
|
|||||||
@ -20,6 +20,7 @@ from typing import TYPE_CHECKING, Any, Final
|
|||||||
|
|
||||||
from steam_backlog_enforcer._command_gate import lock_reason
|
from steam_backlog_enforcer._command_gate import lock_reason
|
||||||
from steam_backlog_enforcer._echo import routed_echo
|
from steam_backlog_enforcer._echo import routed_echo
|
||||||
|
from steam_backlog_enforcer._fail_safe import FAIL_SAFE_ERRORS
|
||||||
from steam_backlog_enforcer._progress import use_progress
|
from steam_backlog_enforcer._progress import use_progress
|
||||||
from steam_backlog_enforcer._prompter import PromptAbortedError, use_prompter
|
from steam_backlog_enforcer._prompter import PromptAbortedError, use_prompter
|
||||||
from steam_backlog_enforcer.config import Config, State, _atomic_write
|
from steam_backlog_enforcer.config import Config, State, _atomic_write
|
||||||
@ -208,13 +209,17 @@ def run_job(job_dir: Path) -> int:
|
|||||||
outcome = _failed(exc.message, EXIT_REFUSED)
|
outcome = _failed(exc.message, EXIT_REFUSED)
|
||||||
except PrivilegedViaDaemonError as exc:
|
except PrivilegedViaDaemonError as exc:
|
||||||
outcome = _failed(str(exc), EXIT_REFUSED)
|
outcome = _failed(str(exc), EXIT_REFUSED)
|
||||||
# Catch-all on purpose: every job ends with a result, however it fails.
|
except FAIL_SAFE_ERRORS as exc:
|
||||||
except Exception as exc: # pylint: disable=broad-exception-caught
|
|
||||||
logger.exception("Job %s crashed", job_dir.name)
|
logger.exception("Job %s crashed", job_dir.name)
|
||||||
outcome = _failed(f"{type(exc).__name__}: {exc}")
|
outcome = _failed(f"{type(exc).__name__}: {exc}")
|
||||||
# SystemExit from outside a handler, etc.: still write the result.
|
# SystemExit from outside a handler: still write the result.
|
||||||
except BaseException as exc: # pylint: disable=broad-exception-caught
|
except SystemExit as exc:
|
||||||
logger.exception("Job %s stopped", job_dir.name)
|
logger.exception("Job %s stopped", job_dir.name)
|
||||||
outcome = _failed(f"{type(exc).__name__}: {exc}")
|
outcome = _failed(f"{type(exc).__name__}: {exc}")
|
||||||
|
# A bug: the job still ends with a result, then the process fails loudly.
|
||||||
|
except BaseException as exc:
|
||||||
|
logger.exception("Job %s crashed on a bug", job_dir.name)
|
||||||
|
_finish(job_dir, writer, _failed(f"{type(exc).__name__}: {exc}"))
|
||||||
|
raise
|
||||||
_finish(job_dir, writer, outcome)
|
_finish(job_dir, writer, outcome)
|
||||||
return outcome.exit_code
|
return outcome.exit_code
|
||||||
|
|||||||
@ -102,13 +102,13 @@ def cmd_reset(config: Config, state: State) -> None:
|
|||||||
state.current_app_id = None
|
state.current_app_id = None
|
||||||
state.current_game_name = ""
|
state.current_game_name = ""
|
||||||
state.finished_app_ids = []
|
state.finished_app_ids = []
|
||||||
state.manual_pick_app_id = None
|
state.legacy_pick.app_id = None
|
||||||
state.manual_pick_game_name = ""
|
state.legacy_pick.game_name = ""
|
||||||
state.manual_pick_started_at = ""
|
state.legacy_pick.started_at = ""
|
||||||
state.manual_picks = []
|
state.manual_picks = []
|
||||||
state.current_assigned_at = ""
|
state.assignment.current_assigned_at = ""
|
||||||
state.last_assigned_at = {}
|
state.assignment.last_assigned_at = {}
|
||||||
state.released_at = {}
|
state.assignment.released_at = {}
|
||||||
state.save()
|
state.save()
|
||||||
_echo("State reset. Store left blocked: open a timed window with 'unblock'.")
|
_echo("State reset. Store left blocked: open a timed window with 'unblock'.")
|
||||||
|
|
||||||
|
|||||||
@ -123,7 +123,7 @@ def abandonable_state(app_id: int = 100, started_at: str = RECENT_PICK) -> State
|
|||||||
"""
|
"""
|
||||||
state = locked_state(app_id=app_id, started_at=started_at)
|
state = locked_state(app_id=app_id, started_at=started_at)
|
||||||
state.current_app_id = app_id
|
state.current_app_id = app_id
|
||||||
state.current_game_name = state.manual_pick_game_name
|
state.current_game_name = state.legacy_pick.game_name
|
||||||
return state
|
return state
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
42
steam_backlog_enforcer/tests/_release_helpers.py
Normal file
42
steam_backlog_enforcer/tests/_release_helpers.py
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
"""Shared builders for the release-lifecycle and tampering tests."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
import json
|
||||||
|
|
||||||
|
from steam_backlog_enforcer import config as config_mod
|
||||||
|
from steam_backlog_enforcer.steam_api import AchievementInfo, GameInfo
|
||||||
|
from steam_backlog_enforcer.tests._main_helpers import STARTED_AT
|
||||||
|
|
||||||
|
RELEASED = datetime(2026, 9, 20, tzinfo=UTC)
|
||||||
|
|
||||||
|
|
||||||
|
def pick(app_id: int, **extra: str) -> dict[str, object]:
|
||||||
|
"""Build one manual-pick entry started a day ago."""
|
||||||
|
return {
|
||||||
|
"app_id": app_id,
|
||||||
|
"game_name": f"G{app_id}",
|
||||||
|
"started_at": STARTED_AT,
|
||||||
|
} | dict(extra.items())
|
||||||
|
|
||||||
|
|
||||||
|
def game(app_id: int, *unlock_times: int, hours: float = 5.0) -> GameInfo:
|
||||||
|
"""Build a GameInfo with one unlocked achievement per epoch given."""
|
||||||
|
return GameInfo(
|
||||||
|
app_id=app_id,
|
||||||
|
name=f"G{app_id}",
|
||||||
|
total_achievements=10,
|
||||||
|
unlocked_achievements=len(unlock_times),
|
||||||
|
playtime_minutes=60,
|
||||||
|
completionist_hours=hours,
|
||||||
|
achievements=[
|
||||||
|
AchievementInfo(f"a{t}", f"A{t}", achieved=True, unlock_time=t)
|
||||||
|
for t in unlock_times
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def write_state(data: dict[str, object]) -> None:
|
||||||
|
"""Write raw JSON to the (conftest-redirected) state file."""
|
||||||
|
config_mod.STATE_FILE.write_text(json.dumps(data), encoding="utf-8")
|
||||||
@ -22,6 +22,16 @@ BLOCK = "steam_backlog_enforcer._total_block"
|
|||||||
NOW_PATCH = "steam_backlog_enforcer._research_window.now"
|
NOW_PATCH = "steam_backlog_enforcer._research_window.now"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class SteamMocks:
|
||||||
|
"""The pass's Steam package effects."""
|
||||||
|
|
||||||
|
installed: MagicMock
|
||||||
|
kill: MagicMock
|
||||||
|
uninstall: MagicMock
|
||||||
|
purge: MagicMock
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class Mocks:
|
class Mocks:
|
||||||
"""The collaborators of one pass, all stand-ins."""
|
"""The collaborators of one pass, all stand-ins."""
|
||||||
@ -30,14 +40,11 @@ class Mocks:
|
|||||||
reconcile: MagicMock
|
reconcile: MagicMock
|
||||||
launchers: MagicMock
|
launchers: MagicMock
|
||||||
counted: MagicMock
|
counted: MagicMock
|
||||||
steam_installed: MagicMock
|
|
||||||
enforce: MagicMock
|
enforce: MagicMock
|
||||||
guard: MagicMock
|
guard: MagicMock
|
||||||
notify: MagicMock
|
notify: MagicMock
|
||||||
restore_store: MagicMock
|
restore_store: MagicMock
|
||||||
steam_kill: MagicMock
|
steam: SteamMocks
|
||||||
steam_uninstall: MagicMock
|
|
||||||
steam_purge: MagicMock
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
@ -63,14 +70,11 @@ def tm(total_block_paths: Paths) -> Iterator[Mocks]:
|
|||||||
reconcile,
|
reconcile,
|
||||||
launchers,
|
launchers,
|
||||||
counted,
|
counted,
|
||||||
installed,
|
|
||||||
enforce,
|
enforce,
|
||||||
guard,
|
guard,
|
||||||
notify,
|
notify,
|
||||||
restore_store,
|
restore_store,
|
||||||
steam_kill,
|
SteamMocks(installed, steam_kill, steam_uninstall, steam_purge),
|
||||||
steam_uninstall,
|
|
||||||
steam_purge,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -5,6 +5,7 @@ from __future__ import annotations
|
|||||||
from dataclasses import replace
|
from dataclasses import replace
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._flat_record import from_flat
|
||||||
from steam_backlog_enforcer._web_dataset import WebGame
|
from steam_backlog_enforcer._web_dataset import WebGame
|
||||||
from steam_backlog_enforcer.steam_api import GameInfo
|
from steam_backlog_enforcer.steam_api import GameInfo
|
||||||
|
|
||||||
@ -25,23 +26,23 @@ def _gi(**over: object) -> GameInfo:
|
|||||||
|
|
||||||
|
|
||||||
def _wg(**over: object) -> WebGame:
|
def _wg(**over: object) -> WebGame:
|
||||||
"""Build a WebGame with field overrides."""
|
"""Build a WebGame with overrides named by its flat (served) keys."""
|
||||||
base = WebGame(
|
base = {
|
||||||
app_id=1,
|
"app_id": 1,
|
||||||
name="Game1",
|
"name": "Game1",
|
||||||
completion_pct=0.0,
|
"completion_pct": 0.0,
|
||||||
playtime_minutes=60,
|
"playtime_minutes": 60,
|
||||||
rush_hours=10.0,
|
"rush_hours": 10.0,
|
||||||
leisure_hours=20.0,
|
"leisure_hours": 20.0,
|
||||||
worst_hours=25.0,
|
"worst_hours": 25.0,
|
||||||
count_comp=20,
|
"count_comp": 20,
|
||||||
comp_100_count=5,
|
"comp_100_count": 5,
|
||||||
hltb_game_id=0,
|
"hltb_game_id": 0,
|
||||||
protondb_tier="gold",
|
"protondb_tier": "gold",
|
||||||
protondb_trending_tier="gold",
|
"protondb_trending_tier": "gold",
|
||||||
protondb_score=0.8,
|
"protondb_score": 0.8,
|
||||||
)
|
}
|
||||||
return replace(base, **over)
|
return from_flat(WebGame, base | over)
|
||||||
|
|
||||||
|
|
||||||
def _complete_game(
|
def _complete_game(
|
||||||
|
|||||||
@ -2,10 +2,12 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from contextlib import contextmanager
|
||||||
|
import threading
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
from steam_backlog_enforcer import _web_process
|
from steam_backlog_enforcer import _web_process, _web_server
|
||||||
from steam_backlog_enforcer._web_process import _server
|
from steam_backlog_enforcer._web_process import _server
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
@ -23,3 +25,19 @@ def clean_process_state() -> Iterator[None]:
|
|||||||
yield
|
yield
|
||||||
_web_process.RETIRING.clear()
|
_web_process.RETIRING.clear()
|
||||||
_server.clear()
|
_server.clear()
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def running_server() -> Iterator[_web_server.WebServer]:
|
||||||
|
"""Serve on an ephemeral loopback port in a thread."""
|
||||||
|
server = _web_server.create_server("127.0.0.1", 0)
|
||||||
|
thread = threading.Thread(
|
||||||
|
target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True
|
||||||
|
)
|
||||||
|
thread.start()
|
||||||
|
try:
|
||||||
|
yield server
|
||||||
|
finally:
|
||||||
|
server.shutdown()
|
||||||
|
server.server_close()
|
||||||
|
thread.join(timeout=2)
|
||||||
|
|||||||
@ -9,6 +9,7 @@ from steam_backlog_enforcer._actions import (
|
|||||||
apply_manual_pick,
|
apply_manual_pick,
|
||||||
is_manual_pick_locked,
|
is_manual_pick_locked,
|
||||||
)
|
)
|
||||||
|
from steam_backlog_enforcer._config_groups import LegacyManualPick
|
||||||
from steam_backlog_enforcer._manual_pick_lifecycle import manual_pick_age_days
|
from steam_backlog_enforcer._manual_pick_lifecycle import manual_pick_age_days
|
||||||
from steam_backlog_enforcer.config import State
|
from steam_backlog_enforcer.config import State
|
||||||
from steam_backlog_enforcer.tests._manual_pick_rows import iso_days_ago, pick_row
|
from steam_backlog_enforcer.tests._manual_pick_rows import iso_days_ago, pick_row
|
||||||
@ -77,18 +78,16 @@ class TestLegacyManualPickMigration:
|
|||||||
"""Test legacy pick is migrated on load."""
|
"""Test legacy pick is migrated on load."""
|
||||||
started = iso_days_ago(1)
|
started = iso_days_ago(1)
|
||||||
State(
|
State(
|
||||||
manual_pick_app_id=5,
|
legacy_pick=LegacyManualPick(5, "Legacy", started),
|
||||||
manual_pick_game_name="Legacy",
|
|
||||||
manual_pick_started_at=started,
|
|
||||||
).save()
|
).save()
|
||||||
|
|
||||||
loaded = State.load()
|
loaded = State.load()
|
||||||
assert loaded.manual_picks == [
|
assert loaded.manual_picks == [
|
||||||
{"app_id": 5, "game_name": "Legacy", "started_at": started}
|
{"app_id": 5, "game_name": "Legacy", "started_at": started}
|
||||||
]
|
]
|
||||||
assert loaded.manual_pick_app_id is None
|
assert loaded.legacy_pick.app_id is None
|
||||||
assert loaded.manual_pick_game_name == ""
|
assert loaded.legacy_pick.game_name == ""
|
||||||
assert loaded.manual_pick_started_at == ""
|
assert loaded.legacy_pick.started_at == ""
|
||||||
assert is_manual_pick_locked(loaded) is True
|
assert is_manual_pick_locked(loaded) is True
|
||||||
|
|
||||||
def test_new_format_is_left_alone(self) -> None:
|
def test_new_format_is_left_alone(self) -> None:
|
||||||
|
|||||||
@ -15,6 +15,7 @@ from steam_backlog_enforcer._assignment_progress import (
|
|||||||
release_game,
|
release_game,
|
||||||
release_verdict,
|
release_verdict,
|
||||||
)
|
)
|
||||||
|
from steam_backlog_enforcer._config_groups import AssignmentTimes
|
||||||
from steam_backlog_enforcer.config import State
|
from steam_backlog_enforcer.config import State
|
||||||
from steam_backlog_enforcer.steam_api import AchievementInfo, GameInfo
|
from steam_backlog_enforcer.steam_api import AchievementInfo, GameInfo
|
||||||
|
|
||||||
@ -57,7 +58,7 @@ def assigned_state(app_id: int = 1) -> State:
|
|||||||
return State(
|
return State(
|
||||||
current_app_id=app_id,
|
current_app_id=app_id,
|
||||||
current_game_name="G",
|
current_game_name="G",
|
||||||
current_assigned_at=ASSIGNED.isoformat(),
|
assignment=AssignmentTimes(current_assigned_at=ASSIGNED.isoformat()),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@ -151,8 +152,8 @@ class TestRecordAssignment:
|
|||||||
state = State()
|
state = State()
|
||||||
record_assignment(state, 7, "Seven", at="T")
|
record_assignment(state, 7, "Seven", at="T")
|
||||||
assert (state.current_app_id, state.current_game_name) == (7, "Seven")
|
assert (state.current_app_id, state.current_game_name) == (7, "Seven")
|
||||||
assert state.current_assigned_at == "T"
|
assert state.assignment.current_assigned_at == "T"
|
||||||
assert state.last_assigned_at == {"7": "T"}
|
assert state.assignment.last_assigned_at == {"7": "T"}
|
||||||
assert state.enforcement_started_at == "T"
|
assert state.enforcement_started_at == "T"
|
||||||
|
|
||||||
def test_keeps_the_first_enforcement_start(self) -> None:
|
def test_keeps_the_first_enforcement_start(self) -> None:
|
||||||
@ -160,7 +161,7 @@ class TestRecordAssignment:
|
|||||||
state = State(enforcement_started_at="FIRST")
|
state = State(enforcement_started_at="FIRST")
|
||||||
record_assignment(state, 7, "Seven")
|
record_assignment(state, 7, "Seven")
|
||||||
assert state.enforcement_started_at == "FIRST"
|
assert state.enforcement_started_at == "FIRST"
|
||||||
assert iso_to_epoch(state.current_assigned_at) is not None
|
assert iso_to_epoch(state.assignment.current_assigned_at) is not None
|
||||||
|
|
||||||
|
|
||||||
class TestLastAssignedEpoch:
|
class TestLastAssignedEpoch:
|
||||||
@ -172,7 +173,9 @@ class TestLastAssignedEpoch:
|
|||||||
|
|
||||||
def test_reads_the_stamp(self) -> None:
|
def test_reads_the_stamp(self) -> None:
|
||||||
"""A stored stamp reads back as its epoch seconds."""
|
"""A stored stamp reads back as its epoch seconds."""
|
||||||
state = State(last_assigned_at={"1": ASSIGNED.isoformat()})
|
state = State(
|
||||||
|
assignment=AssignmentTimes(last_assigned_at={"1": ASSIGNED.isoformat()})
|
||||||
|
)
|
||||||
assert last_assigned_epoch(state, 1) == ASSIGNED.timestamp()
|
assert last_assigned_epoch(state, 1) == ASSIGNED.timestamp()
|
||||||
|
|
||||||
|
|
||||||
@ -197,7 +200,7 @@ class TestReleaseGame:
|
|||||||
release_game(state, game(("a", AFTER)))
|
release_game(state, game(("a", AFTER)))
|
||||||
assert state.finished_app_ids == []
|
assert state.finished_app_ids == []
|
||||||
assert state.manual_picks[0]["released_at"]
|
assert state.manual_picks[0]["released_at"]
|
||||||
assert "1" in state.released_at
|
assert "1" in state.assignment.released_at
|
||||||
expiry = datetime.fromisoformat(state.skipped_until["1"])
|
expiry = datetime.fromisoformat(state.skipped_until["1"])
|
||||||
assert expiry > datetime.now(UTC) + timedelta(days=RELEASE_COOLDOWN_DAYS - 1)
|
assert expiry > datetime.now(UTC) + timedelta(days=RELEASE_COOLDOWN_DAYS - 1)
|
||||||
|
|
||||||
|
|||||||
@ -192,14 +192,14 @@ class TestReadingReachesTheRulesAndTheView:
|
|||||||
return_value=resolution,
|
return_value=resolution,
|
||||||
):
|
):
|
||||||
rules = rules_for(Config(), demo=False)
|
rules = rules_for(Config(), demo=False)
|
||||||
assert rules.reading_seconds == HOUR
|
assert rules.breakdown.reading_seconds == HOUR
|
||||||
with patch.object(view, "mounted_targets", return_value=set()):
|
with patch.object(view, "mounted_targets", return_value=set()):
|
||||||
bonuses = view.build_rules(rules)["bonuses"]
|
bonuses = view.build_rules(rules)["bonuses"]
|
||||||
assert bonuses["reading"] == HOUR
|
assert bonuses["reading"] == HOUR
|
||||||
|
|
||||||
def test_a_demo_run_earns_no_reading(self) -> None:
|
def test_a_demo_run_earns_no_reading(self) -> None:
|
||||||
"""A demo run never earns the reading hour."""
|
"""A demo run never earns the reading hour."""
|
||||||
assert rules_for(Config(), demo=True).reading_seconds == 0.0
|
assert rules_for(Config(), demo=True).breakdown.reading_seconds == 0.0
|
||||||
|
|
||||||
def test_a_resolution_defaults_to_no_reading(self) -> None:
|
def test_a_resolution_defaults_to_no_reading(self) -> None:
|
||||||
"""A resolution built without reading defaults to zero."""
|
"""A resolution built without reading defaults to zero."""
|
||||||
|
|||||||
@ -9,6 +9,7 @@ from datetime import datetime
|
|||||||
|
|
||||||
from steam_backlog_enforcer._budget_view import build_rules
|
from steam_backlog_enforcer._budget_view import build_rules
|
||||||
from steam_backlog_enforcer._ledger_earners import registry_for
|
from steam_backlog_enforcer._ledger_earners import registry_for
|
||||||
|
from steam_backlog_enforcer._playtime_record import BudgetBreakdown
|
||||||
from steam_backlog_enforcer._playtime_state import PlaytimeRules
|
from steam_backlog_enforcer._playtime_state import PlaytimeRules
|
||||||
|
|
||||||
|
|
||||||
@ -21,7 +22,7 @@ def test_earners_list_the_registry_with_earned_and_size() -> None:
|
|||||||
count_launchers=False,
|
count_launchers=False,
|
||||||
enforcement=True,
|
enforcement=True,
|
||||||
demo=False,
|
demo=False,
|
||||||
earned_seconds={"leetcode": 3600.0},
|
breakdown=BudgetBreakdown(earned_seconds={"leetcode": 3600.0}),
|
||||||
)
|
)
|
||||||
listed = {e["name"]: e for e in build_rules(rules)["earners"]}
|
listed = {e["name"]: e for e in build_rules(rules)["earners"]}
|
||||||
# The registry in force today (the tutor cutover switches it).
|
# The registry in force today (the tutor cutover switches it).
|
||||||
|
|||||||
@ -176,6 +176,21 @@ class TestHandle:
|
|||||||
for _ in range(_ctl_server.MAX_CONNECTIONS):
|
for _ in range(_ctl_server.MAX_CONNECTIONS):
|
||||||
assert srv.take_slot()
|
assert srv.take_slot()
|
||||||
|
|
||||||
|
def test_a_bug_ends_the_thread_but_frees_the_slot(self) -> None:
|
||||||
|
"""A bug outside FAIL_SAFE_ERRORS escapes; the socket and slot do not leak."""
|
||||||
|
srv = _server()
|
||||||
|
conn = MagicMock()
|
||||||
|
assert srv.take_slot()
|
||||||
|
with (
|
||||||
|
patch.object(_ctl_server, "read_line", return_value=b"x"),
|
||||||
|
patch.object(srv, "dispatch", side_effect=AttributeError("bug")),
|
||||||
|
pytest.raises(AttributeError),
|
||||||
|
):
|
||||||
|
srv.handle(conn, 7)
|
||||||
|
conn.close.assert_called_once()
|
||||||
|
for _ in range(_ctl_server.MAX_CONNECTIONS):
|
||||||
|
assert srv.take_slot()
|
||||||
|
|
||||||
|
|
||||||
class TestDispatch:
|
class TestDispatch:
|
||||||
"""_dispatch never raises."""
|
"""_dispatch never raises."""
|
||||||
@ -197,6 +212,15 @@ class TestDispatch:
|
|||||||
with patch.object(srv, "run", side_effect=RuntimeError("x")):
|
with patch.object(srv, "run", side_effect=RuntimeError("x")):
|
||||||
assert b'"error":"op_failed"' in srv.dispatch(b"", 0)
|
assert b'"error":"op_failed"' in srv.dispatch(b"", 0)
|
||||||
|
|
||||||
|
def test_a_programming_bug_is_loud(self) -> None:
|
||||||
|
"""An error outside FAIL_SAFE_ERRORS is not dressed up as op_failed."""
|
||||||
|
srv = _server()
|
||||||
|
with (
|
||||||
|
patch.object(srv, "run", side_effect=AttributeError("bug")),
|
||||||
|
pytest.raises(AttributeError),
|
||||||
|
):
|
||||||
|
srv.dispatch(b"", 0)
|
||||||
|
|
||||||
def test_run_rejects_unknown(self) -> None:
|
def test_run_rejects_unknown(self) -> None:
|
||||||
"""An unknown op raises CtlError."""
|
"""An unknown op raises CtlError."""
|
||||||
with pytest.raises(CtlError, match="unknown op"):
|
with pytest.raises(CtlError, match="unknown op"):
|
||||||
|
|||||||
54
steam_backlog_enforcer/tests/test_flat_record.py
Normal file
54
steam_backlog_enforcer/tests/test_flat_record.py
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
"""Nested groups behind one flat dict: keys, order and round trip."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._flat_record import (
|
||||||
|
flat_group,
|
||||||
|
flat_keys,
|
||||||
|
from_flat,
|
||||||
|
to_flat,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class _Inner:
|
||||||
|
depth: int = 0
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class _Middle:
|
||||||
|
name: str = ""
|
||||||
|
inner: _Inner = field(default_factory=_Inner, metadata=flat_group(_Inner, "in_"))
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class _Outer:
|
||||||
|
first: int = 0
|
||||||
|
middle: _Middle = field(
|
||||||
|
default_factory=_Middle, metadata=flat_group(_Middle, "mid_")
|
||||||
|
)
|
||||||
|
last: int = 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_nested_groups_flatten_with_joined_prefixes() -> None:
|
||||||
|
"""A group inside a group writes ``outer + inner`` prefixed keys in place."""
|
||||||
|
record = _Outer(1, _Middle("m", _Inner(2)), 3)
|
||||||
|
assert to_flat(record) == {
|
||||||
|
"first": 1,
|
||||||
|
"mid_name": "m",
|
||||||
|
"mid_in_depth": 2,
|
||||||
|
"last": 3,
|
||||||
|
}
|
||||||
|
assert list(to_flat(record)) == ["first", "mid_name", "mid_in_depth", "last"]
|
||||||
|
assert flat_keys(_Outer) == {"first", "mid_name", "mid_in_depth", "last"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_from_flat_round_trips_and_ignores_unknown_keys() -> None:
|
||||||
|
"""Unknown keys are dropped; missing ones take the defaults."""
|
||||||
|
record = _Outer(1, _Middle("m", _Inner(2)), 3)
|
||||||
|
assert from_flat(_Outer, to_flat(record) | {"stray": True}) == record
|
||||||
|
assert from_flat(_Outer, {"mid_in_depth": 5}) == _Outer(
|
||||||
|
middle=_Middle(inner=_Inner(5))
|
||||||
|
)
|
||||||
108
steam_backlog_enforcer/tests/test_flat_records_golden.py
Normal file
108
steam_backlog_enforcer/tests/test_flat_records_golden.py
Normal file
@ -0,0 +1,108 @@
|
|||||||
|
"""Golden round-trips: the persisted files keep their exact flat bytes.
|
||||||
|
|
||||||
|
``Config``, ``State`` and ``PlaytimeState`` group fields into nested
|
||||||
|
dataclasses, but the files on disk stay flat. A fully populated file written
|
||||||
|
by the old flat classes must load and save back byte for byte.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from steam_backlog_enforcer import _playtime_state, config
|
||||||
|
from steam_backlog_enforcer._playtime_state import load_state, save_state
|
||||||
|
|
||||||
|
CONFIG: dict[str, Any] = {
|
||||||
|
"steam_api_key": "KEY",
|
||||||
|
"steam_id": "7656",
|
||||||
|
"block_store": False,
|
||||||
|
"kill_unauthorized_games": False,
|
||||||
|
"uninstall_other_games": False,
|
||||||
|
"desktop_notifications": False,
|
||||||
|
"max_manual_picks": 3,
|
||||||
|
"book_ledger_path": "/b.json",
|
||||||
|
"workout_status_url": "http://127.0.0.1:1/w",
|
||||||
|
"workout_log_path": "/w.json",
|
||||||
|
"leetcode_ledger_path": "/l.json",
|
||||||
|
"leetcode_status_url": "http://127.0.0.1:2/l",
|
||||||
|
"count_launcher_processes": False,
|
||||||
|
"counted_processes": [{"id": "osu", "label": "osu!", "names": ["osu!"]}],
|
||||||
|
"playtime_enforcement": False,
|
||||||
|
}
|
||||||
|
|
||||||
|
STATE: dict[str, Any] = {
|
||||||
|
"current_app_id": 440,
|
||||||
|
"current_game_name": "TF2",
|
||||||
|
"finished_app_ids": [10, 20],
|
||||||
|
"skipped_until": {"30": "2026-11-20T00:00:00+00:00"},
|
||||||
|
"enforcement_started_at": "2026-01-01T00:00:00+00:00",
|
||||||
|
"manual_pick_app_id": None,
|
||||||
|
"manual_pick_game_name": "",
|
||||||
|
"manual_pick_started_at": "",
|
||||||
|
"manual_picks": [
|
||||||
|
{"app_id": 50, "game_name": "Fifty", "started_at": "2026-11-01T00:00:00"}
|
||||||
|
],
|
||||||
|
"current_assigned_at": "2026-11-02T00:00:00+00:00",
|
||||||
|
"last_assigned_at": {
|
||||||
|
"440": "2026-11-02T00:00:00+00:00",
|
||||||
|
"50": "2026-11-01T00:00:00",
|
||||||
|
},
|
||||||
|
"released_at": {"60": "2026-11-03T00:00:00+00:00"},
|
||||||
|
"store_unblocked_until": "2026-11-12T10:00:00+00:00",
|
||||||
|
}
|
||||||
|
|
||||||
|
PLAYTIME: dict[str, Any] = {
|
||||||
|
"schema_version": 1,
|
||||||
|
"day_key": "2026-11-12",
|
||||||
|
"seconds": 120.5,
|
||||||
|
"last_tick_at": 1700000000.0,
|
||||||
|
"blocked_at": 1700000100.0,
|
||||||
|
"per_game": {"app:440": 100.0},
|
||||||
|
"last_credited_key": "app:440",
|
||||||
|
"warned_seconds": [600, 300],
|
||||||
|
"budget_seconds": 7200.0,
|
||||||
|
"shadow_seconds": 30.0,
|
||||||
|
"shadow_budget_seconds": 3600.0,
|
||||||
|
"shadow_per_source": {"media": 30.0},
|
||||||
|
"shadow_paused_seconds": 5.0,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _flat(data: dict[str, Any]) -> str:
|
||||||
|
"""The exact bytes the flat classes wrote."""
|
||||||
|
return json.dumps(data, indent=2) + "\n"
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_round_trips_byte_for_byte() -> None:
|
||||||
|
"""A full config.json loads and saves back unchanged."""
|
||||||
|
config.CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
config.CONFIG_FILE.write_text(_flat(CONFIG), encoding="utf-8")
|
||||||
|
config.Config.load().save()
|
||||||
|
assert config.CONFIG_FILE.read_text(encoding="utf-8") == _flat(CONFIG)
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_defaults_keep_the_flat_shape() -> None:
|
||||||
|
"""A default config writes every flat key, in the old order."""
|
||||||
|
config.Config().save()
|
||||||
|
saved = json.loads(config.CONFIG_FILE.read_text(encoding="utf-8"))
|
||||||
|
assert list(saved) == list(CONFIG)
|
||||||
|
|
||||||
|
|
||||||
|
def test_state_round_trips_byte_for_byte() -> None:
|
||||||
|
"""A full state.json loads and saves back unchanged."""
|
||||||
|
config.STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
config.STATE_FILE.write_text(_flat(STATE), encoding="utf-8")
|
||||||
|
config.State.load().save()
|
||||||
|
assert config.STATE_FILE.read_text(encoding="utf-8") == _flat(STATE)
|
||||||
|
|
||||||
|
|
||||||
|
def test_playtime_state_round_trips_byte_for_byte() -> None:
|
||||||
|
"""A full playtime state file loads and saves back unchanged."""
|
||||||
|
path = _playtime_state.state_path(demo=True)
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
path.write_text(_flat(PLAYTIME), encoding="utf-8")
|
||||||
|
state = load_state(demo=True)
|
||||||
|
assert state is not None
|
||||||
|
save_state(state, demo=True)
|
||||||
|
assert path.read_text(encoding="utf-8") == _flat(PLAYTIME)
|
||||||
@ -8,6 +8,8 @@ from __future__ import annotations
|
|||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
from steam_backlog_enforcer._game_names import (
|
from steam_backlog_enforcer._game_names import (
|
||||||
_is_protected_name,
|
_is_protected_name,
|
||||||
_normalize_game_name,
|
_normalize_game_name,
|
||||||
@ -69,6 +71,17 @@ class TestProtectedNameStems:
|
|||||||
stems = _protected_name_stems()
|
stems = _protected_name_stems()
|
||||||
assert stems == []
|
assert stems == []
|
||||||
|
|
||||||
|
def test_a_programming_bug_is_loud(self) -> None:
|
||||||
|
"""An error outside FAIL_SAFE_ERRORS propagates."""
|
||||||
|
with (
|
||||||
|
patch(
|
||||||
|
"steam_backlog_enforcer.config.State.load",
|
||||||
|
side_effect=AttributeError("bug"),
|
||||||
|
),
|
||||||
|
pytest.raises(AttributeError, match="bug"),
|
||||||
|
):
|
||||||
|
_protected_name_stems()
|
||||||
|
|
||||||
|
|
||||||
class TestIsProtectedName:
|
class TestIsProtectedName:
|
||||||
"""Tests for _is_protected_name."""
|
"""Tests for _is_protected_name."""
|
||||||
|
|||||||
@ -109,7 +109,7 @@ class TestRulesHold:
|
|||||||
):
|
):
|
||||||
rules = rules_for(Config(), demo=False)
|
rules = rules_for(Config(), demo=False)
|
||||||
assert rules.budget_seconds == 10 * HOUR
|
assert rules.budget_seconds == 10 * HOUR
|
||||||
assert rules.budget_reason.endswith("; held at 10.0h (earned earlier today)")
|
assert rules.breakdown.reason.endswith("; held at 10.0h (earned earlier today)")
|
||||||
|
|
||||||
def test_a_higher_live_answer_wins_silently(self) -> None:
|
def test_a_higher_live_answer_wins_silently(self) -> None:
|
||||||
"""A live budget above the held one wins with no held note."""
|
"""A live budget above the held one wins with no held note."""
|
||||||
@ -118,4 +118,4 @@ class TestRulesHold:
|
|||||||
):
|
):
|
||||||
rules = rules_for(Config(), demo=False)
|
rules = rules_for(Config(), demo=False)
|
||||||
assert rules.budget_seconds > HOUR
|
assert rules.budget_seconds > HOUR
|
||||||
assert "held at" not in rules.budget_reason
|
assert "held at" not in rules.breakdown.reason
|
||||||
|
|||||||
@ -19,7 +19,11 @@ from steam_backlog_enforcer._hltb_failures import (
|
|||||||
Breaker,
|
Breaker,
|
||||||
failure_summary_lines,
|
failure_summary_lines,
|
||||||
)
|
)
|
||||||
from steam_backlog_enforcer._hltb_search_one import _search_one, _SearchCtx
|
from steam_backlog_enforcer._hltb_search_one import (
|
||||||
|
_AuthSlot,
|
||||||
|
_search_one,
|
||||||
|
_SearchCtx,
|
||||||
|
)
|
||||||
from steam_backlog_enforcer._hltb_types import _AuthInfo
|
from steam_backlog_enforcer._hltb_types import _AuthInfo
|
||||||
from steam_backlog_enforcer.tests._hltb_fake_transport import MATCH, FakeResp
|
from steam_backlog_enforcer.tests._hltb_fake_transport import MATCH, FakeResp
|
||||||
|
|
||||||
@ -84,10 +88,9 @@ def _ctx(session: _RotatingSession, clock: _Clock) -> _SearchCtx:
|
|||||||
search_url="https://example.invalid/api/finder",
|
search_url="https://example.invalid/api/finder",
|
||||||
headers={"x-auth-token": "tok0", "x-hp-key": "hp", "x-hp-val": "v0"},
|
headers={"x-auth-token": "tok0", "x-hp-key": "hp", "x-hp-val": "v0"},
|
||||||
cache={},
|
cache={},
|
||||||
auth=_AuthInfo("tok0", "hp", "v0"),
|
auth=_AuthSlot(_AuthInfo("tok0", "hp", "v0"), issued_at=clock.t),
|
||||||
counter={"done": 0, "found": 0, "failed": 0},
|
counter={"done": 0, "found": 0, "failed": 0},
|
||||||
breaker=Breaker(),
|
breaker=Breaker(),
|
||||||
auth_at=clock.t,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@ -119,7 +122,7 @@ def test_aged_token_is_refreshed_into_headers_and_body() -> None:
|
|||||||
_lookups(ctx, clock, [0, _AGE + 1])
|
_lookups(ctx, clock, [0, _AGE + 1])
|
||||||
assert session.gets == 1
|
assert session.gets == 1
|
||||||
assert session.posts == [("tok0", "v0"), ("tok1", "v1")]
|
assert session.posts == [("tok0", "v0"), ("tok1", "v1")]
|
||||||
assert ctx.auth == _AuthInfo("tok1", "hp", "v1")
|
assert ctx.auth.info == _AuthInfo("tok1", "hp", "v1")
|
||||||
|
|
||||||
|
|
||||||
def test_one_refresh_per_elapsed_interval() -> None:
|
def test_one_refresh_per_elapsed_interval() -> None:
|
||||||
|
|||||||
@ -15,7 +15,11 @@ import pytest
|
|||||||
from steam_backlog_enforcer import _hltb_pacing
|
from steam_backlog_enforcer import _hltb_pacing
|
||||||
from steam_backlog_enforcer._hltb_comp_extract import _fetch_detail_one
|
from steam_backlog_enforcer._hltb_comp_extract import _fetch_detail_one
|
||||||
from steam_backlog_enforcer._hltb_failures import BREAKER_LIMIT, shared_breaker
|
from steam_backlog_enforcer._hltb_failures import BREAKER_LIMIT, shared_breaker
|
||||||
from steam_backlog_enforcer._hltb_search_one import _search_one, _SearchCtx
|
from steam_backlog_enforcer._hltb_search_one import (
|
||||||
|
_AuthSlot,
|
||||||
|
_search_one,
|
||||||
|
_SearchCtx,
|
||||||
|
)
|
||||||
from steam_backlog_enforcer._hltb_types import MAX_CONCURRENT, _AuthInfo
|
from steam_backlog_enforcer._hltb_types import MAX_CONCURRENT, _AuthInfo
|
||||||
from steam_backlog_enforcer.tests._hltb_fake_transport import (
|
from steam_backlog_enforcer.tests._hltb_fake_transport import (
|
||||||
MATCH,
|
MATCH,
|
||||||
@ -49,7 +53,7 @@ def _ctx(session: FakeSession) -> _SearchCtx:
|
|||||||
search_url="https://example.invalid/api/finder",
|
search_url="https://example.invalid/api/finder",
|
||||||
headers={},
|
headers={},
|
||||||
cache={},
|
cache={},
|
||||||
auth=_AuthInfo("t"),
|
auth=_AuthSlot(_AuthInfo("t")),
|
||||||
counter={"done": 0, "found": 0, "failed": 0},
|
counter={"done": 0, "found": 0, "failed": 0},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@ -47,7 +47,7 @@ class TestSearchOne:
|
|||||||
ctx = _ctx(make_session(FakeResponse(200, hit("TF2", 180000, 0))))
|
ctx = _ctx(make_session(FakeResponse(200, hit("TF2", 180000, 0))))
|
||||||
result = run_search(ctx)
|
result = run_search(ctx)
|
||||||
assert result is not None
|
assert result is not None
|
||||||
assert 440 not in ctx.extras.hltb_game_id
|
assert 440 not in ctx.results.extras.hltb_game_id
|
||||||
|
|
||||||
def test_not_found(self) -> None:
|
def test_not_found(self) -> None:
|
||||||
"""Test not found."""
|
"""Test not found."""
|
||||||
|
|||||||
@ -15,7 +15,12 @@ from steam_backlog_enforcer._hltb_failures import (
|
|||||||
failure_summary_lines,
|
failure_summary_lines,
|
||||||
reset_failures,
|
reset_failures,
|
||||||
)
|
)
|
||||||
from steam_backlog_enforcer._hltb_search_one import _search_one, _SearchCtx
|
from steam_backlog_enforcer._hltb_search_one import (
|
||||||
|
_AuthSlot,
|
||||||
|
_search_one,
|
||||||
|
_SearchCtx,
|
||||||
|
_SearchResults,
|
||||||
|
)
|
||||||
from steam_backlog_enforcer._hltb_types import _AuthInfo, _HLTBExtras
|
from steam_backlog_enforcer._hltb_types import _AuthInfo, _HLTBExtras
|
||||||
from steam_backlog_enforcer.tests._hltb_fake_transport import (
|
from steam_backlog_enforcer.tests._hltb_fake_transport import (
|
||||||
MATCH,
|
MATCH,
|
||||||
@ -25,15 +30,19 @@ from steam_backlog_enforcer.tests._hltb_fake_transport import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _saved(ctx: _SearchCtx) -> tuple[float, int, int]:
|
||||||
|
"""Game 1's cached hours, poll count and completionist count."""
|
||||||
|
return ctx.cache[1], ctx.results.polls[1], ctx.results.extras.count_comp[1]
|
||||||
|
|
||||||
|
|
||||||
def _ctx(session: FakeSession, total: int = 1) -> _SearchCtx:
|
def _ctx(session: FakeSession, total: int = 1) -> _SearchCtx:
|
||||||
return _SearchCtx(
|
return _SearchCtx(
|
||||||
session=cast("aiohttp.ClientSession", session),
|
session=cast("aiohttp.ClientSession", session),
|
||||||
search_url="https://example.invalid/api/finder",
|
search_url="https://example.invalid/api/finder",
|
||||||
headers={},
|
headers={},
|
||||||
cache={1: 50.0},
|
cache={1: 50.0},
|
||||||
polls={1: 120},
|
results=_SearchResults(polls={1: 120}, extras=_HLTBExtras(count_comp={1: 900})),
|
||||||
extras=_HLTBExtras(count_comp={1: 900}),
|
auth=_AuthSlot(_AuthInfo("t")),
|
||||||
auth=_AuthInfo("t"),
|
|
||||||
counter={"done": 0, "found": 0, "failed": 0},
|
counter={"done": 0, "found": 0, "failed": 0},
|
||||||
total=total,
|
total=total,
|
||||||
)
|
)
|
||||||
@ -64,8 +73,8 @@ def test_failed_search_keeps_prior_entry(kind: str) -> None:
|
|||||||
ctx = _ctx(FakeSession({"*": _FAILURES[kind]}))
|
ctx = _ctx(FakeSession({"*": _FAILURES[kind]}))
|
||||||
_run(ctx, 1, "Celeste")
|
_run(ctx, 1, "Celeste")
|
||||||
assert ctx.cache[1] == 50.0
|
assert ctx.cache[1] == 50.0
|
||||||
assert ctx.polls[1] == 120
|
assert ctx.results.polls[1] == 120
|
||||||
assert ctx.extras.count_comp[1] == 900
|
assert ctx.results.extras.count_comp[1] == 900
|
||||||
assert ctx.counter["failed"] == 1
|
assert ctx.counter["failed"] == 1
|
||||||
assert ctx.counter["found"] == 0
|
assert ctx.counter["found"] == 0
|
||||||
|
|
||||||
@ -75,7 +84,11 @@ def test_failed_variant_blocks_a_miss() -> None:
|
|||||||
routes = {"Vox Populi Poland 2023": FakeResp(200, NO_MATCH), "*": FakeResp(429)}
|
routes = {"Vox Populi Poland 2023": FakeResp(200, NO_MATCH), "*": FakeResp(429)}
|
||||||
ctx = _ctx(FakeSession(routes))
|
ctx = _ctx(FakeSession(routes))
|
||||||
_run(ctx, 1, "Vox Populi: Poland 2023")
|
_run(ctx, 1, "Vox Populi: Poland 2023")
|
||||||
assert (ctx.cache[1], ctx.polls[1], ctx.extras.count_comp[1]) == (50.0, 120, 900)
|
assert _saved(ctx) == (
|
||||||
|
50.0,
|
||||||
|
120,
|
||||||
|
900,
|
||||||
|
)
|
||||||
assert ctx.counter["failed"] == 1
|
assert ctx.counter["failed"] == 1
|
||||||
|
|
||||||
|
|
||||||
@ -84,7 +97,11 @@ def test_match_beats_failed_sibling_variant() -> None:
|
|||||||
routes = {"Vox Populi Poland 2023": FakeResp(429), "*": FakeResp(200, MATCH)}
|
routes = {"Vox Populi Poland 2023": FakeResp(429), "*": FakeResp(200, MATCH)}
|
||||||
ctx = _ctx(FakeSession(routes))
|
ctx = _ctx(FakeSession(routes))
|
||||||
_run(ctx, 1, "Vox Populi: Poland 2023")
|
_run(ctx, 1, "Vox Populi: Poland 2023")
|
||||||
assert (ctx.cache[1], ctx.polls[1], ctx.extras.count_comp[1]) == (10.0, 42, 300)
|
assert _saved(ctx) == (
|
||||||
|
10.0,
|
||||||
|
42,
|
||||||
|
300,
|
||||||
|
)
|
||||||
assert ctx.counter == {"done": 1, "found": 1, "failed": 0}
|
assert ctx.counter == {"done": 1, "found": 1, "failed": 0}
|
||||||
|
|
||||||
|
|
||||||
@ -92,7 +109,11 @@ def test_clean_no_match_still_writes_a_miss() -> None:
|
|||||||
"""Every variant answered 200 with nothing usable: that is a real miss."""
|
"""Every variant answered 200 with nothing usable: that is a real miss."""
|
||||||
ctx = _ctx(FakeSession({"*": FakeResp(200, NO_MATCH)}))
|
ctx = _ctx(FakeSession({"*": FakeResp(200, NO_MATCH)}))
|
||||||
_run(ctx, 1, "Vox Populi: Poland 2023")
|
_run(ctx, 1, "Vox Populi: Poland 2023")
|
||||||
assert (ctx.cache[1], ctx.polls[1], ctx.extras.count_comp[1]) == (-1, 0, 0)
|
assert _saved(ctx) == (
|
||||||
|
-1,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
)
|
||||||
assert ctx.counter["failed"] == 0
|
assert ctx.counter["failed"] == 0
|
||||||
|
|
||||||
|
|
||||||
@ -101,8 +122,8 @@ def test_failure_without_prior_entry_writes_nothing() -> None:
|
|||||||
ctx = _ctx(FakeSession({"*": FakeResp(429)}))
|
ctx = _ctx(FakeSession({"*": FakeResp(429)}))
|
||||||
_run(ctx, 2, "Celeste")
|
_run(ctx, 2, "Celeste")
|
||||||
assert 2 not in ctx.cache
|
assert 2 not in ctx.cache
|
||||||
assert 2 not in ctx.polls
|
assert 2 not in ctx.results.polls
|
||||||
assert 2 not in ctx.extras.count_comp
|
assert 2 not in ctx.results.extras.count_comp
|
||||||
assert ctx.counter == {"done": 1, "found": 0, "failed": 1}
|
assert ctx.counter == {"done": 1, "found": 0, "failed": 1}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -229,3 +229,15 @@ class TestRunJob:
|
|||||||
events = read_events(path)
|
events = read_events(path)
|
||||||
assert [e["type"] for e in events[-2:]] == ["result", "state"]
|
assert [e["type"] for e in events[-2:]] == ["result", "state"]
|
||||||
assert events[-1]["state"] == state
|
assert events[-1]["state"] == state
|
||||||
|
|
||||||
|
def test_a_programming_bug_writes_a_result_then_raises(self) -> None:
|
||||||
|
"""An error outside FAIL_SAFE_ERRORS still ends the job, then is loud."""
|
||||||
|
path = make_job()
|
||||||
|
with (
|
||||||
|
patch(_RUN, side_effect=AttributeError("bug")),
|
||||||
|
pytest.raises(AttributeError, match="bug"),
|
||||||
|
):
|
||||||
|
_runner.run_job(path)
|
||||||
|
result = json.loads((path / RESULT_NAME).read_text(encoding="utf-8"))
|
||||||
|
assert (result["state"], result["summary"]) == ("failed", "AttributeError: bug")
|
||||||
|
assert read_events(path)[-1]["state"] == "failed"
|
||||||
|
|||||||
@ -183,6 +183,16 @@ class TestEnforce:
|
|||||||
killer.enforce(_SPENT, _RULES, verdict=_verdict(None), stamp=stamp)
|
killer.enforce(_SPENT, _RULES, verdict=_verdict(None), stamp=stamp)
|
||||||
assert sum("Leisure kill failed" in r.message for r in caplog.records) == 1
|
assert sum("Leisure kill failed" in r.message for r in caplog.records) == 1
|
||||||
|
|
||||||
|
def test_a_programming_bug_is_loud(self) -> None:
|
||||||
|
"""An error outside FAIL_SAFE_ERRORS propagates instead of being logged."""
|
||||||
|
killer = LeisureKiller(None)
|
||||||
|
with (
|
||||||
|
patch.object(_leisure_kill, "sweep_targets", side_effect=AttributeError),
|
||||||
|
pytest.raises(AttributeError),
|
||||||
|
):
|
||||||
|
for stamp in range(0, 34, 3):
|
||||||
|
killer.enforce(_SPENT, _RULES, verdict=_verdict(None), stamp=stamp)
|
||||||
|
|
||||||
def test_a_failed_sigkill_is_retried_and_logged_once_delivered(
|
def test_a_failed_sigkill_is_retried_and_logged_once_delivered(
|
||||||
self, proc: Path, kill: MagicMock
|
self, proc: Path, kill: MagicMock
|
||||||
) -> None:
|
) -> None:
|
||||||
|
|||||||
@ -152,7 +152,7 @@ class TestLeisureBilled:
|
|||||||
tick = Tick(now=now, interval=3.0, owners={}, verdict=verdict)
|
tick = Tick(now=now, interval=3.0, owners={}, verdict=verdict)
|
||||||
state = leisure_billed(state, tick)
|
state = leisure_billed(state, tick)
|
||||||
moved = state.seconds - before.seconds
|
moved = state.seconds - before.seconds
|
||||||
assert moved == state.shadow_seconds - before.shadow_seconds
|
assert moved == state.shadow.seconds - before.shadow.seconds
|
||||||
|
|
||||||
|
|
||||||
class TestDormantBilling:
|
class TestDormantBilling:
|
||||||
|
|||||||
@ -108,7 +108,7 @@ class TestDormant:
|
|||||||
state, spy = _tick({})
|
state, spy = _tick({})
|
||||||
assert spy.calls == []
|
assert spy.calls == []
|
||||||
# Games-only, exactly as before: the fail-closed shadow does not bill.
|
# Games-only, exactly as before: the fail-closed shadow does not bill.
|
||||||
assert (state.seconds, state.shadow_seconds) == (0.0, 3.0)
|
assert (state.seconds, state.shadow.seconds) == (0.0, 3.0)
|
||||||
|
|
||||||
def test_games_still_bill_games_only(self) -> None:
|
def test_games_still_bill_games_only(self) -> None:
|
||||||
"""A running game is billed per game as before."""
|
"""A running game is billed per game as before."""
|
||||||
@ -130,8 +130,8 @@ class TestLive:
|
|||||||
"""The fail-closed shadow count becomes the billed count."""
|
"""The fail-closed shadow count becomes the billed count."""
|
||||||
_go_live(tmp_path)
|
_go_live(tmp_path)
|
||||||
state, spy = _tick({})
|
state, spy = _tick({})
|
||||||
assert state.seconds == state.shadow_seconds == 3.0
|
assert state.seconds == state.shadow.seconds == 3.0
|
||||||
assert state.shadow_per_source == {_shadow.FAILCLOSED_KEY: 3.0}
|
assert state.shadow.per_source == {_shadow.FAILCLOSED_KEY: 3.0}
|
||||||
assert len(spy.calls) == 1
|
assert len(spy.calls) == 1
|
||||||
_seen, rules = spy.calls[0]
|
_seen, rules = spy.calls[0]
|
||||||
assert rules.leisure
|
assert rules.leisure
|
||||||
@ -141,7 +141,7 @@ class TestLive:
|
|||||||
_go_live(tmp_path)
|
_go_live(tmp_path)
|
||||||
with patch.object(_shadow, "paused_by", return_value="i3lock"):
|
with patch.object(_shadow, "paused_by", return_value="i3lock"):
|
||||||
state, _ = _tick({7: "app:440"})
|
state, _ = _tick({7: "app:440"})
|
||||||
assert (state.seconds, state.shadow_paused_seconds) == (0.0, 3.0)
|
assert (state.seconds, state.shadow.paused_seconds) == (0.0, 3.0)
|
||||||
|
|
||||||
def test_at_zero_the_cutoff_says_leisure_and_kills_run(
|
def test_at_zero_the_cutoff_says_leisure_and_kills_run(
|
||||||
self, tmp_path: Path, notify: MagicMock
|
self, tmp_path: Path, notify: MagicMock
|
||||||
|
|||||||
@ -131,7 +131,7 @@ _RECENT_PICK = (datetime.now(UTC) - timedelta(days=1)).isoformat()
|
|||||||
def _abandonable_state(app_id: int = 100, started_at: str = _RECENT_PICK) -> State:
|
def _abandonable_state(app_id: int = 100, started_at: str = _RECENT_PICK) -> State:
|
||||||
state = locked_state(app_id=app_id, started_at=started_at)
|
state = locked_state(app_id=app_id, started_at=started_at)
|
||||||
state.current_app_id = app_id
|
state.current_app_id = app_id
|
||||||
state.current_game_name = state.manual_pick_game_name
|
state.current_game_name = state.legacy_pick.game_name
|
||||||
return state
|
return state
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -56,8 +56,8 @@ def _state_on(
|
|||||||
state = State(manual_picks=manual_picks or [])
|
state = State(manual_picks=manual_picks or [])
|
||||||
state.current_app_id = app_id
|
state.current_app_id = app_id
|
||||||
state.current_game_name = name
|
state.current_game_name = name
|
||||||
state.current_assigned_at = STARTED_AT
|
state.assignment.current_assigned_at = STARTED_AT
|
||||||
state.last_assigned_at[str(app_id)] = STARTED_AT
|
state.assignment.last_assigned_at[str(app_id)] = STARTED_AT
|
||||||
return state
|
return state
|
||||||
|
|
||||||
|
|
||||||
@ -123,7 +123,7 @@ class TestKeep:
|
|||||||
assert kept["released_at"]
|
assert kept["released_at"]
|
||||||
assert active_manual_picks(state) == []
|
assert active_manual_picks(state) == []
|
||||||
assert state.finished_app_ids == []
|
assert state.finished_app_ids == []
|
||||||
assert state.released_at == {}
|
assert state.assignment.released_at == {}
|
||||||
|
|
||||||
def test_allowed_games_are_not_offered(self) -> None:
|
def test_allowed_games_are_not_offered(self) -> None:
|
||||||
"""Games already allowed are not offered as candidates."""
|
"""Games already allowed are not offered as candidates."""
|
||||||
|
|||||||
@ -15,6 +15,7 @@ import pytest
|
|||||||
from steam_backlog_enforcer import _mcp_actions as mcp_actions
|
from steam_backlog_enforcer import _mcp_actions as mcp_actions
|
||||||
from steam_backlog_enforcer._actions import allowed_app_ids, apply_manual_pick
|
from steam_backlog_enforcer._actions import allowed_app_ids, apply_manual_pick
|
||||||
from steam_backlog_enforcer._allowed_games import active_manual_picks
|
from steam_backlog_enforcer._allowed_games import active_manual_picks
|
||||||
|
from steam_backlog_enforcer._config_groups import AssignmentTimes
|
||||||
from steam_backlog_enforcer.config import Config, State
|
from steam_backlog_enforcer.config import Config, State
|
||||||
from steam_backlog_enforcer.main import cmd_pick_manual
|
from steam_backlog_enforcer.main import cmd_pick_manual
|
||||||
from steam_backlog_enforcer.tests._main_helpers import STARTED_AT
|
from steam_backlog_enforcer.tests._main_helpers import STARTED_AT
|
||||||
@ -36,7 +37,7 @@ def _state(*kept: tuple[int, str], current: tuple[int, str] = (1, "Current")) ->
|
|||||||
return State(
|
return State(
|
||||||
current_app_id=current[0],
|
current_app_id=current[0],
|
||||||
current_game_name=current[1],
|
current_game_name=current[1],
|
||||||
current_assigned_at=STARTED_AT,
|
assignment=AssignmentTimes(current_assigned_at=STARTED_AT),
|
||||||
manual_picks=[_kept(a, n) for a, n in kept],
|
manual_picks=[_kept(a, n) for a, n in kept],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@ -13,6 +13,7 @@ from datetime import (
|
|||||||
)
|
)
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._config_groups import PlaytimePolicy
|
||||||
from steam_backlog_enforcer._playtime import (
|
from steam_backlog_enforcer._playtime import (
|
||||||
_policy,
|
_policy,
|
||||||
)
|
)
|
||||||
@ -28,8 +29,8 @@ NOW = datetime(2026, 7, 27, 20, 0, tzinfo=LOCAL)
|
|||||||
TODAY = "2026-07-27"
|
TODAY = "2026-07-27"
|
||||||
|
|
||||||
|
|
||||||
def _rules(*, demo: bool = False, **cfg: object) -> object:
|
def _rules(*, demo: bool = False, **policy: bool) -> object:
|
||||||
return rules_for(Config(**cfg), demo=demo)
|
return rules_for(Config(playtime=PlaytimePolicy(**policy)), demo=demo)
|
||||||
|
|
||||||
|
|
||||||
class TestPolicyBelowBudget:
|
class TestPolicyBelowBudget:
|
||||||
|
|||||||
@ -6,6 +6,7 @@ from dataclasses import FrozenInstanceError
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._config_groups import PlaytimePolicy
|
||||||
from steam_backlog_enforcer._playtime_state import rules_for
|
from steam_backlog_enforcer._playtime_state import rules_for
|
||||||
from steam_backlog_enforcer.config import Config
|
from steam_backlog_enforcer.config import Config
|
||||||
from steam_backlog_enforcer.tests._no_workout_http import fixed_budget
|
from steam_backlog_enforcer.tests._no_workout_http import fixed_budget
|
||||||
@ -41,26 +42,36 @@ class TestRulesFor:
|
|||||||
"""count_launcher_processes becomes count_launchers."""
|
"""count_launcher_processes becomes count_launchers."""
|
||||||
assert (
|
assert (
|
||||||
rules_for(
|
rules_for(
|
||||||
Config(count_launcher_processes=False), demo=False
|
Config(playtime=PlaytimePolicy(count_launcher_processes=False)),
|
||||||
|
demo=False,
|
||||||
).count_launchers
|
).count_launchers
|
||||||
is False
|
is False
|
||||||
)
|
)
|
||||||
assert (
|
assert (
|
||||||
rules_for(Config(count_launcher_processes=True), demo=False).count_launchers
|
rules_for(
|
||||||
|
Config(playtime=PlaytimePolicy(count_launcher_processes=True)),
|
||||||
|
demo=False,
|
||||||
|
).count_launchers
|
||||||
is True
|
is True
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_enforcement_toggle_is_carried_through(self) -> None:
|
def test_enforcement_toggle_is_carried_through(self) -> None:
|
||||||
"""playtime_enforcement off becomes enforcement off."""
|
"""playtime_enforcement off becomes enforcement off."""
|
||||||
assert (
|
assert (
|
||||||
rules_for(Config(playtime_enforcement=False), demo=False).enforcement
|
rules_for(
|
||||||
|
Config(playtime=PlaytimePolicy(playtime_enforcement=False)), demo=False
|
||||||
|
).enforcement
|
||||||
is False
|
is False
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_demo_uses_the_same_qualifying_predicate(self) -> None:
|
def test_demo_uses_the_same_qualifying_predicate(self) -> None:
|
||||||
"""Demo may differ in budget and warnings only."""
|
"""Demo may differ in budget and warnings only."""
|
||||||
prod = rules_for(Config(count_launcher_processes=True), demo=False)
|
prod = rules_for(
|
||||||
demo = rules_for(Config(count_launcher_processes=True), demo=True)
|
Config(playtime=PlaytimePolicy(count_launcher_processes=True)), demo=False
|
||||||
|
)
|
||||||
|
demo = rules_for(
|
||||||
|
Config(playtime=PlaytimePolicy(count_launcher_processes=True)), demo=True
|
||||||
|
)
|
||||||
assert prod.count_launchers == demo.count_launchers
|
assert prod.count_launchers == demo.count_launchers
|
||||||
|
|
||||||
def test_rules_are_frozen(self) -> None:
|
def test_rules_are_frozen(self) -> None:
|
||||||
|
|||||||
@ -16,6 +16,7 @@ from unittest.mock import patch
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._config_groups import EarnSources
|
||||||
from steam_backlog_enforcer._reading_bonus import (
|
from steam_backlog_enforcer._reading_bonus import (
|
||||||
read_ledger_read_today,
|
read_ledger_read_today,
|
||||||
read_today,
|
read_today,
|
||||||
@ -199,7 +200,9 @@ class TestTheMemo:
|
|||||||
def test_reads_the_configured_ledger(self, tmp_path: Path) -> None:
|
def test_reads_the_configured_ledger(self, tmp_path: Path) -> None:
|
||||||
"""read_today reads the ledger named in the config."""
|
"""read_today reads the ledger named in the config."""
|
||||||
ledger = write_ledger(tmp_path, [reading(when=_now())])
|
ledger = write_ledger(tmp_path, [reading(when=_now())])
|
||||||
assert read_today(Config(book_ledger_path=str(ledger))) is True
|
assert (
|
||||||
|
read_today(Config(earn=EarnSources(book_ledger_path=str(ledger)))) is True
|
||||||
|
)
|
||||||
|
|
||||||
def test_a_cached_answer_is_served_without_a_reread(self) -> None:
|
def test_a_cached_answer_is_served_without_a_reread(self) -> None:
|
||||||
"""A cached answer is served without reading the ledger again."""
|
"""A cached answer is served without reading the ledger again."""
|
||||||
@ -225,4 +228,4 @@ class TestTheMemo:
|
|||||||
|
|
||||||
def test_the_default_path_is_book_guards(self) -> None:
|
def test_the_default_path_is_book_guards(self) -> None:
|
||||||
"""The default ledger path points at book_guard's ledger."""
|
"""The default ledger path points at book_guard's ledger."""
|
||||||
assert Config().book_ledger_path.endswith("book_guard/ledger.json")
|
assert Config().earn.book_ledger_path.endswith("book_guard/ledger.json")
|
||||||
|
|||||||
@ -1,14 +1,13 @@
|
|||||||
"""A released game stays playable until the user explicitly picks another.
|
"""A released game stays playable until the user explicitly picks another.
|
||||||
|
|
||||||
Covers the state upgrade, the allowed set, abandoning, pick order, tampering
|
Covers the state upgrade, the allowed set, abandoning and pick order under
|
||||||
and the ``check`` command under the "one new achievement" rule.
|
the "one new achievement" rule (tampering: ``test_release_tampering``).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import UTC, datetime, timedelta
|
|
||||||
import json
|
import json
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
from steam_backlog_enforcer import config as config_mod
|
from steam_backlog_enforcer import config as config_mod
|
||||||
from steam_backlog_enforcer._actions import (
|
from steam_backlog_enforcer._actions import (
|
||||||
@ -17,45 +16,16 @@ from steam_backlog_enforcer._actions import (
|
|||||||
is_manual_pick_locked,
|
is_manual_pick_locked,
|
||||||
)
|
)
|
||||||
from steam_backlog_enforcer._allowed_games import drop_inactive_picks
|
from steam_backlog_enforcer._allowed_games import drop_inactive_picks
|
||||||
|
from steam_backlog_enforcer._config_groups import AssignmentTimes
|
||||||
from steam_backlog_enforcer._manual_pick_lifecycle import abandon_manual_pick
|
from steam_backlog_enforcer._manual_pick_lifecycle import abandon_manual_pick
|
||||||
from steam_backlog_enforcer._scanning_assign import _open_candidates
|
from steam_backlog_enforcer._scanning_assign import _open_candidates
|
||||||
from steam_backlog_enforcer._scanning_tampering import _check_game_tampering
|
from steam_backlog_enforcer.config import State
|
||||||
from steam_backlog_enforcer.config import Config, State
|
|
||||||
from steam_backlog_enforcer.scanning import do_check
|
|
||||||
from steam_backlog_enforcer.steam_api import AchievementInfo, GameInfo
|
|
||||||
from steam_backlog_enforcer.tests._main_helpers import EXPIRED_AT, STARTED_AT
|
from steam_backlog_enforcer.tests._main_helpers import EXPIRED_AT, STARTED_AT
|
||||||
|
from steam_backlog_enforcer.tests._release_helpers import (
|
||||||
RELEASED = datetime(2026, 9, 20, tzinfo=UTC)
|
game,
|
||||||
|
pick,
|
||||||
|
write_state,
|
||||||
def pick(app_id: int, **extra: str) -> dict[str, object]:
|
)
|
||||||
"""Build one manual-pick entry started a day ago."""
|
|
||||||
return {
|
|
||||||
"app_id": app_id,
|
|
||||||
"game_name": f"G{app_id}",
|
|
||||||
"started_at": STARTED_AT,
|
|
||||||
} | dict(extra.items())
|
|
||||||
|
|
||||||
|
|
||||||
def game(app_id: int, *unlock_times: int, hours: float = 5.0) -> GameInfo:
|
|
||||||
"""Build a GameInfo with one unlocked achievement per epoch given."""
|
|
||||||
return GameInfo(
|
|
||||||
app_id=app_id,
|
|
||||||
name=f"G{app_id}",
|
|
||||||
total_achievements=10,
|
|
||||||
unlocked_achievements=len(unlock_times),
|
|
||||||
playtime_minutes=60,
|
|
||||||
completionist_hours=hours,
|
|
||||||
achievements=[
|
|
||||||
AchievementInfo(f"a{t}", f"A{t}", achieved=True, unlock_time=t)
|
|
||||||
for t in unlock_times
|
|
||||||
],
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def write_state(data: dict[str, object]) -> None:
|
|
||||||
"""Write raw JSON to the (conftest-redirected) state file."""
|
|
||||||
config_mod.STATE_FILE.write_text(json.dumps(data), encoding="utf-8")
|
|
||||||
|
|
||||||
|
|
||||||
class TestLoadBackfill:
|
class TestLoadBackfill:
|
||||||
@ -65,16 +35,21 @@ class TestLoadBackfill:
|
|||||||
"""A plain assignment gets one timestamp that later loads keep."""
|
"""A plain assignment gets one timestamp that later loads keep."""
|
||||||
write_state({"current_app_id": 5, "current_game_name": "G5"})
|
write_state({"current_app_id": 5, "current_game_name": "G5"})
|
||||||
first = State.load()
|
first = State.load()
|
||||||
assert first.current_assigned_at
|
assert first.assignment.current_assigned_at
|
||||||
assert State.load().current_assigned_at == first.current_assigned_at
|
assert (
|
||||||
assert first.last_assigned_at == {"5": first.current_assigned_at}
|
State.load().assignment.current_assigned_at
|
||||||
|
== first.assignment.current_assigned_at
|
||||||
|
)
|
||||||
|
assert first.assignment.last_assigned_at == {
|
||||||
|
"5": first.assignment.current_assigned_at
|
||||||
|
}
|
||||||
|
|
||||||
def test_current_pick_keeps_its_pick_time(self) -> None:
|
def test_current_pick_keeps_its_pick_time(self) -> None:
|
||||||
"""An assigned pick is timed from when it was picked."""
|
"""An assigned pick is timed from when it was picked."""
|
||||||
write_state({"current_app_id": 5, "manual_picks": [pick(5), pick(6)]})
|
write_state({"current_app_id": 5, "manual_picks": [pick(5), pick(6)]})
|
||||||
state = State.load()
|
state = State.load()
|
||||||
assert state.current_assigned_at == STARTED_AT
|
assert state.assignment.current_assigned_at == STARTED_AT
|
||||||
assert state.last_assigned_at == {"5": STARTED_AT, "6": STARTED_AT}
|
assert state.assignment.last_assigned_at == {"5": STARTED_AT, "6": STARTED_AT}
|
||||||
|
|
||||||
def test_legacy_pick_migration_is_persisted(self) -> None:
|
def test_legacy_pick_migration_is_persisted(self) -> None:
|
||||||
"""A legacy single-pick state is migrated and written back."""
|
"""A legacy single-pick state is migrated and written back."""
|
||||||
@ -120,7 +95,9 @@ class TestReleasedPicksStayPlayable:
|
|||||||
with patch.object(State, "save"):
|
with patch.object(State, "save"):
|
||||||
assert apply_manual_pick(state, 4, "G4", max_picks=1) is None
|
assert apply_manual_pick(state, 4, "G4", max_picks=1) is None
|
||||||
assert allowed_app_ids(state) == {2, 4}
|
assert allowed_app_ids(state) == {2, 4}
|
||||||
assert state.current_assigned_at == state.manual_picks[-1]["started_at"]
|
assert (
|
||||||
|
state.assignment.current_assigned_at == state.manual_picks[-1]["started_at"]
|
||||||
|
)
|
||||||
|
|
||||||
def test_released_pick_can_be_abandoned(self) -> None:
|
def test_released_pick_can_be_abandoned(self) -> None:
|
||||||
"""A released pick can be abandoned and the active pick takes over."""
|
"""A released pick can be abandoned and the active pick takes over."""
|
||||||
@ -130,14 +107,24 @@ class TestReleasedPicksStayPlayable:
|
|||||||
with patch.object(State, "save"):
|
with patch.object(State, "save"):
|
||||||
assert abandon_manual_pick(state, 2) is True
|
assert abandon_manual_pick(state, 2) is True
|
||||||
# The active pick inherits the assignment, timed from its pick.
|
# The active pick inherits the assignment, timed from its pick.
|
||||||
assert (state.current_app_id, state.current_assigned_at) == (3, STARTED_AT)
|
assert (state.current_app_id, state.assignment.current_assigned_at) == (
|
||||||
|
3,
|
||||||
|
STARTED_AT,
|
||||||
|
)
|
||||||
|
|
||||||
def test_abandoning_the_last_pick_clears_the_assignment(self) -> None:
|
def test_abandoning_the_last_pick_clears_the_assignment(self) -> None:
|
||||||
"""Abandoning the only pick clears the assignment."""
|
"""Abandoning the only pick clears the assignment."""
|
||||||
state = State(current_app_id=2, current_assigned_at="T", manual_picks=[pick(2)])
|
state = State(
|
||||||
|
current_app_id=2,
|
||||||
|
assignment=AssignmentTimes(current_assigned_at="T"),
|
||||||
|
manual_picks=[pick(2)],
|
||||||
|
)
|
||||||
with patch.object(State, "save"):
|
with patch.object(State, "save"):
|
||||||
abandon_manual_pick(state, 2)
|
abandon_manual_pick(state, 2)
|
||||||
assert (state.current_app_id, state.current_assigned_at) == (None, "")
|
assert (state.current_app_id, state.assignment.current_assigned_at) == (
|
||||||
|
None,
|
||||||
|
"",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class TestPickOrder:
|
class TestPickOrder:
|
||||||
@ -146,10 +133,12 @@ class TestPickOrder:
|
|||||||
def test_least_recently_assigned_first_then_shortest(self) -> None:
|
def test_least_recently_assigned_first_then_shortest(self) -> None:
|
||||||
"""Never-assigned games come first, then the oldest assignment."""
|
"""Never-assigned games come first, then the oldest assignment."""
|
||||||
state = State(
|
state = State(
|
||||||
last_assigned_at={
|
assignment=AssignmentTimes(
|
||||||
"1": "2026-09-01T00:00:00+00:00",
|
last_assigned_at={
|
||||||
"2": "2026-08-01T00:00:00+00:00",
|
"1": "2026-09-01T00:00:00+00:00",
|
||||||
}
|
"2": "2026-08-01T00:00:00+00:00",
|
||||||
|
}
|
||||||
|
)
|
||||||
)
|
)
|
||||||
games = [game(1, hours=1.0), game(2, hours=2.0), game(3, hours=9.0)]
|
games = [game(1, hours=1.0), game(2, hours=2.0), game(3, hours=9.0)]
|
||||||
with patch(
|
with patch(
|
||||||
@ -158,82 +147,3 @@ class TestPickOrder:
|
|||||||
):
|
):
|
||||||
order = [g.app_id for g in _open_candidates(games, state)]
|
order = [g.app_id for g in _open_candidates(games, state)]
|
||||||
assert order == [3, 2, 1]
|
assert order == [3, 2, 1]
|
||||||
|
|
||||||
|
|
||||||
class TestTamperingAfterRelease:
|
|
||||||
"""Unlocks after a release are tampering; earlier ones are not."""
|
|
||||||
|
|
||||||
def entry(self) -> dict[str, object]:
|
|
||||||
"""Return the catalogue entry for the released game."""
|
|
||||||
return {
|
|
||||||
"app_id": 7,
|
|
||||||
"name": "G7",
|
|
||||||
"total_achievements": 10,
|
|
||||||
"unlocked_achievements": 0,
|
|
||||||
"playtime_minutes": 60,
|
|
||||||
}
|
|
||||||
|
|
||||||
def check(self, *unlock_times: int) -> tuple[str, int, int] | None:
|
|
||||||
"""Run the tampering check against a refresh with these unlocks."""
|
|
||||||
client = MagicMock()
|
|
||||||
client.refresh_single_game.return_value = game(7, *unlock_times)
|
|
||||||
state = State(current_app_id=1, released_at={"7": RELEASED.isoformat()})
|
|
||||||
return _check_game_tampering(client, self.entry(), state)
|
|
||||||
|
|
||||||
def test_unlocks_earned_while_assigned_are_legitimate(self) -> None:
|
|
||||||
"""Unlocks earned while the game was assigned are legitimate."""
|
|
||||||
before = int((RELEASED - timedelta(hours=1)).timestamp())
|
|
||||||
assert self.check(before, before) is None
|
|
||||||
|
|
||||||
def test_unlocks_after_release_are_flagged(self) -> None:
|
|
||||||
"""Unlocks made after the release are flagged as tampering."""
|
|
||||||
before = int((RELEASED - timedelta(hours=1)).timestamp())
|
|
||||||
after = int((RELEASED + timedelta(hours=1)).timestamp())
|
|
||||||
assert self.check(before, after) == ("G7", 7, 1)
|
|
||||||
|
|
||||||
def test_unreadable_game_is_not_flagged(self) -> None:
|
|
||||||
"""A game whose refresh fails is not flagged."""
|
|
||||||
client = MagicMock()
|
|
||||||
client.refresh_single_game.return_value = None
|
|
||||||
assert _check_game_tampering(client, self.entry(), State()) is None
|
|
||||||
|
|
||||||
|
|
||||||
class TestCheckCommand:
|
|
||||||
"""The check command applies the one-new-achievement rule."""
|
|
||||||
|
|
||||||
def run_check(self, state: State, refreshed: GameInfo) -> MagicMock:
|
|
||||||
"""Run do_check with every side effect patched; return the pick mock."""
|
|
||||||
client = MagicMock()
|
|
||||||
client.refresh_single_game.return_value = refreshed
|
|
||||||
with (
|
|
||||||
patch(
|
|
||||||
"steam_backlog_enforcer.scanning.SteamAPIClient", return_value=client
|
|
||||||
),
|
|
||||||
patch("steam_backlog_enforcer.scanning._echo"),
|
|
||||||
patch("steam_backlog_enforcer.scanning.report_completion"),
|
|
||||||
patch("steam_backlog_enforcer.scanning.detect_tampering"),
|
|
||||||
patch("steam_backlog_enforcer.scanning.send_notification"),
|
|
||||||
patch("steam_backlog_enforcer.scanning.load_snapshot", return_value=[]),
|
|
||||||
patch("steam_backlog_enforcer.scanning.pick_next_game") as mock_pick,
|
|
||||||
patch.object(State, "save"),
|
|
||||||
):
|
|
||||||
do_check(Config(), state)
|
|
||||||
return mock_pick
|
|
||||||
|
|
||||||
def test_new_achievement_releases_and_keeps_the_game(self) -> None:
|
|
||||||
"""A new achievement releases the game and keeps it assigned."""
|
|
||||||
state = State(current_app_id=7, current_assigned_at=RELEASED.isoformat())
|
|
||||||
after = int((RELEASED + timedelta(hours=1)).timestamp())
|
|
||||||
self.run_check(state, game(7, after))
|
|
||||||
assert "7" in state.released_at
|
|
||||||
assert state.finished_app_ids == []
|
|
||||||
# No snapshot, so no replacement: the game stays assigned.
|
|
||||||
assert state.current_app_id == 7
|
|
||||||
|
|
||||||
def test_no_new_achievement_changes_nothing(self) -> None:
|
|
||||||
"""No new achievement leaves the state and the pick untouched."""
|
|
||||||
state = State(current_app_id=7, current_assigned_at=RELEASED.isoformat())
|
|
||||||
before = int((RELEASED - timedelta(hours=1)).timestamp())
|
|
||||||
mock_pick = self.run_check(state, game(7, before))
|
|
||||||
assert state.released_at == {}
|
|
||||||
mock_pick.assert_not_called()
|
|
||||||
|
|||||||
107
steam_backlog_enforcer/tests/test_release_tampering.py
Normal file
107
steam_backlog_enforcer/tests/test_release_tampering.py
Normal file
@ -0,0 +1,107 @@
|
|||||||
|
"""Tampering checks after a game was released, and the check command."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import timedelta
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._config_groups import AssignmentTimes
|
||||||
|
from steam_backlog_enforcer._scanning_tampering import _check_game_tampering
|
||||||
|
from steam_backlog_enforcer.config import Config, State
|
||||||
|
from steam_backlog_enforcer.scanning import do_check
|
||||||
|
from steam_backlog_enforcer.tests._release_helpers import (
|
||||||
|
RELEASED,
|
||||||
|
game,
|
||||||
|
)
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from steam_backlog_enforcer.steam_api import GameInfo
|
||||||
|
|
||||||
|
|
||||||
|
class TestTamperingAfterRelease:
|
||||||
|
"""Unlocks after a release are tampering; earlier ones are not."""
|
||||||
|
|
||||||
|
def entry(self) -> dict[str, object]:
|
||||||
|
"""Return the catalogue entry for the released game."""
|
||||||
|
return {
|
||||||
|
"app_id": 7,
|
||||||
|
"name": "G7",
|
||||||
|
"total_achievements": 10,
|
||||||
|
"unlocked_achievements": 0,
|
||||||
|
"playtime_minutes": 60,
|
||||||
|
}
|
||||||
|
|
||||||
|
def check(self, *unlock_times: int) -> tuple[str, int, int] | None:
|
||||||
|
"""Run the tampering check against a refresh with these unlocks."""
|
||||||
|
client = MagicMock()
|
||||||
|
client.refresh_single_game.return_value = game(7, *unlock_times)
|
||||||
|
state = State(
|
||||||
|
current_app_id=1,
|
||||||
|
assignment=AssignmentTimes(released_at={"7": RELEASED.isoformat()}),
|
||||||
|
)
|
||||||
|
return _check_game_tampering(client, self.entry(), state)
|
||||||
|
|
||||||
|
def test_unlocks_earned_while_assigned_are_legitimate(self) -> None:
|
||||||
|
"""Unlocks earned while the game was assigned are legitimate."""
|
||||||
|
before = int((RELEASED - timedelta(hours=1)).timestamp())
|
||||||
|
assert self.check(before, before) is None
|
||||||
|
|
||||||
|
def test_unlocks_after_release_are_flagged(self) -> None:
|
||||||
|
"""Unlocks made after the release are flagged as tampering."""
|
||||||
|
before = int((RELEASED - timedelta(hours=1)).timestamp())
|
||||||
|
after = int((RELEASED + timedelta(hours=1)).timestamp())
|
||||||
|
assert self.check(before, after) == ("G7", 7, 1)
|
||||||
|
|
||||||
|
def test_unreadable_game_is_not_flagged(self) -> None:
|
||||||
|
"""A game whose refresh fails is not flagged."""
|
||||||
|
client = MagicMock()
|
||||||
|
client.refresh_single_game.return_value = None
|
||||||
|
assert _check_game_tampering(client, self.entry(), State()) is None
|
||||||
|
|
||||||
|
|
||||||
|
class TestCheckCommand:
|
||||||
|
"""The check command applies the one-new-achievement rule."""
|
||||||
|
|
||||||
|
def run_check(self, state: State, refreshed: GameInfo) -> MagicMock:
|
||||||
|
"""Run do_check with every side effect patched; return the pick mock."""
|
||||||
|
client = MagicMock()
|
||||||
|
client.refresh_single_game.return_value = refreshed
|
||||||
|
with (
|
||||||
|
patch(
|
||||||
|
"steam_backlog_enforcer.scanning.SteamAPIClient", return_value=client
|
||||||
|
),
|
||||||
|
patch("steam_backlog_enforcer.scanning._echo"),
|
||||||
|
patch("steam_backlog_enforcer.scanning.report_completion"),
|
||||||
|
patch("steam_backlog_enforcer.scanning.detect_tampering"),
|
||||||
|
patch("steam_backlog_enforcer.scanning.send_notification"),
|
||||||
|
patch("steam_backlog_enforcer.scanning.load_snapshot", return_value=[]),
|
||||||
|
patch("steam_backlog_enforcer.scanning.pick_next_game") as mock_pick,
|
||||||
|
patch.object(State, "save"),
|
||||||
|
):
|
||||||
|
do_check(Config(), state)
|
||||||
|
return mock_pick
|
||||||
|
|
||||||
|
def test_new_achievement_releases_and_keeps_the_game(self) -> None:
|
||||||
|
"""A new achievement releases the game and keeps it assigned."""
|
||||||
|
state = State(
|
||||||
|
current_app_id=7,
|
||||||
|
assignment=AssignmentTimes(current_assigned_at=RELEASED.isoformat()),
|
||||||
|
)
|
||||||
|
after = int((RELEASED + timedelta(hours=1)).timestamp())
|
||||||
|
self.run_check(state, game(7, after))
|
||||||
|
assert "7" in state.assignment.released_at
|
||||||
|
assert state.finished_app_ids == []
|
||||||
|
# No snapshot, so no replacement: the game stays assigned.
|
||||||
|
assert state.current_app_id == 7
|
||||||
|
|
||||||
|
def test_no_new_achievement_changes_nothing(self) -> None:
|
||||||
|
"""No new achievement leaves the state and the pick untouched."""
|
||||||
|
state = State(
|
||||||
|
current_app_id=7,
|
||||||
|
assignment=AssignmentTimes(current_assigned_at=RELEASED.isoformat()),
|
||||||
|
)
|
||||||
|
before = int((RELEASED - timedelta(hours=1)).timestamp())
|
||||||
|
mock_pick = self.run_check(state, game(7, before))
|
||||||
|
assert state.assignment.released_at == {}
|
||||||
|
mock_pick.assert_not_called()
|
||||||
@ -72,9 +72,9 @@ class TestOpenWindow:
|
|||||||
"""Test that the destructive half of the block stays off."""
|
"""Test that the destructive half of the block stays off."""
|
||||||
window.write_record(make_record())
|
window.write_record(make_record())
|
||||||
run_pass()
|
run_pass()
|
||||||
tm.steam_kill.assert_not_called()
|
tm.steam.kill.assert_not_called()
|
||||||
tm.steam_uninstall.assert_not_called()
|
tm.steam.uninstall.assert_not_called()
|
||||||
tm.steam_purge.assert_not_called()
|
tm.steam.purge.assert_not_called()
|
||||||
|
|
||||||
def test_other_launchers_and_counted_games_are_still_killed(
|
def test_other_launchers_and_counted_games_are_still_killed(
|
||||||
self, tm: Mocks
|
self, tm: Mocks
|
||||||
@ -105,7 +105,7 @@ class TestOpenWindow:
|
|||||||
self, tm: Mocks
|
self, tm: Mocks
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Test that the install gap does not scan an absent library."""
|
"""Test that the install gap does not scan an absent library."""
|
||||||
tm.steam_installed.return_value = False
|
tm.steam.installed.return_value = False
|
||||||
window.write_record(make_record())
|
window.write_record(make_record())
|
||||||
run_pass()
|
run_pass()
|
||||||
tm.enforce.assert_not_called()
|
tm.enforce.assert_not_called()
|
||||||
|
|||||||
@ -9,6 +9,7 @@ from leisure_watch.facts import Focus, Now, Reason
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from steam_backlog_enforcer import _shadow
|
from steam_backlog_enforcer import _shadow
|
||||||
|
from steam_backlog_enforcer._playtime_record import ShadowLedger
|
||||||
from steam_backlog_enforcer._playtime_state import PlaytimeState
|
from steam_backlog_enforcer._playtime_state import PlaytimeState
|
||||||
from steam_backlog_enforcer._shadow import (
|
from steam_backlog_enforcer._shadow import (
|
||||||
FAILCLOSED_KEY,
|
FAILCLOSED_KEY,
|
||||||
@ -142,9 +143,9 @@ class TestShadowAccumulate:
|
|||||||
def test_paused_goes_to_paused_seconds_only(self) -> None:
|
def test_paused_goes_to_paused_seconds_only(self) -> None:
|
||||||
"""A paused tick only adds to paused seconds."""
|
"""A paused tick only adds to paused seconds."""
|
||||||
out = self._bill(_state(), ShadowVerdict("i3lock", ()))
|
out = self._bill(_state(), ShadowVerdict("i3lock", ()))
|
||||||
assert out.shadow_paused_seconds == 3.0
|
assert out.shadow.paused_seconds == 3.0
|
||||||
assert out.shadow_seconds == 0.0
|
assert out.shadow.seconds == 0.0
|
||||||
assert out.shadow_per_source == {}
|
assert out.shadow.per_source == {}
|
||||||
|
|
||||||
def test_free_bills_nothing(self) -> None:
|
def test_free_bills_nothing(self) -> None:
|
||||||
"""A free tick leaves the state unchanged."""
|
"""A free tick leaves the state unchanged."""
|
||||||
@ -154,16 +155,16 @@ class TestShadowAccumulate:
|
|||||||
def test_one_source_takes_the_whole_tick(self) -> None:
|
def test_one_source_takes_the_whole_tick(self) -> None:
|
||||||
"""A single source is billed the whole tick."""
|
"""A single source is billed the whole tick."""
|
||||||
out = self._bill(_state(), ShadowVerdict(None, ("app:440",)))
|
out = self._bill(_state(), ShadowVerdict(None, ("app:440",)))
|
||||||
assert out.shadow_seconds == 3.0
|
assert out.shadow.seconds == 3.0
|
||||||
assert out.shadow_per_source == {"app:440": 3.0}
|
assert out.shadow.per_source == {"app:440": 3.0}
|
||||||
|
|
||||||
def test_overlapping_sources_bill_once_and_split(self) -> None:
|
def test_overlapping_sources_bill_once_and_split(self) -> None:
|
||||||
"""Overlapping sources share one tick, never billing it twice."""
|
"""Overlapping sources share one tick, never billing it twice."""
|
||||||
state = _state(shadow_per_source={"a": 1.0}, shadow_seconds=1.0)
|
state = _state(shadow=ShadowLedger(per_source={"a": 1.0}, seconds=1.0))
|
||||||
out = self._bill(state, ShadowVerdict(None, ("a", "b")))
|
out = self._bill(state, ShadowVerdict(None, ("a", "b")))
|
||||||
assert out.shadow_seconds == 4.0
|
assert out.shadow.seconds == 4.0
|
||||||
assert out.shadow_per_source == {"a": 2.5, "b": 1.5}
|
assert out.shadow.per_source == {"a": 2.5, "b": 1.5}
|
||||||
assert sum(out.shadow_per_source.values()) <= out.shadow_seconds + 1e-9
|
assert sum(out.shadow.per_source.values()) <= out.shadow.seconds + 1e-9
|
||||||
|
|
||||||
def test_the_delta_is_clamped_like_the_enforced_one(self) -> None:
|
def test_the_delta_is_clamped_like_the_enforced_one(self) -> None:
|
||||||
"""A long gap is clamped exactly like the enforced budget."""
|
"""A long gap is clamped exactly like the enforced budget."""
|
||||||
@ -173,7 +174,7 @@ class TestShadowAccumulate:
|
|||||||
interval=3.0,
|
interval=3.0,
|
||||||
verdict=ShadowVerdict(None, (FAILCLOSED_KEY,)),
|
verdict=ShadowVerdict(None, (FAILCLOSED_KEY,)),
|
||||||
)
|
)
|
||||||
assert out.shadow_seconds == 6.0
|
assert out.shadow.seconds == 6.0
|
||||||
|
|
||||||
def test_never_touches_enforced_fields(self) -> None:
|
def test_never_touches_enforced_fields(self) -> None:
|
||||||
"""Shadow billing leaves every enforced field as it was."""
|
"""Shadow billing leaves every enforced field as it was."""
|
||||||
|
|||||||
@ -16,6 +16,7 @@ from steam_backlog_enforcer import _mcp_gaming_time as mcp_gaming_time
|
|||||||
from steam_backlog_enforcer._budget_resolve import resolve_budget
|
from steam_backlog_enforcer._budget_resolve import resolve_budget
|
||||||
from steam_backlog_enforcer._gaming_days import held_shadow_today
|
from steam_backlog_enforcer._gaming_days import held_shadow_today
|
||||||
from steam_backlog_enforcer._playtime import playtime_tick
|
from steam_backlog_enforcer._playtime import playtime_tick
|
||||||
|
from steam_backlog_enforcer._playtime_record import ShadowLedger
|
||||||
from steam_backlog_enforcer._playtime_state import (
|
from steam_backlog_enforcer._playtime_state import (
|
||||||
PlaytimeState,
|
PlaytimeState,
|
||||||
load_state,
|
load_state,
|
||||||
@ -84,12 +85,16 @@ class TestHeldShadow:
|
|||||||
|
|
||||||
def test_same_day_holds_the_high_water(self) -> None:
|
def test_same_day_holds_the_high_water(self) -> None:
|
||||||
"""A stored budget from today is held."""
|
"""A stored budget from today is held."""
|
||||||
stored = PlaytimeState(day_key=_TODAY, shadow_budget_seconds=9 * HOUR)
|
stored = PlaytimeState(
|
||||||
|
day_key=_TODAY, shadow=ShadowLedger(budget_seconds=9 * HOUR)
|
||||||
|
)
|
||||||
assert held_shadow_today(stored, _NOW) == 9 * HOUR
|
assert held_shadow_today(stored, _NOW) == 9 * HOUR
|
||||||
|
|
||||||
def test_another_day_or_no_state_holds_nothing(self) -> None:
|
def test_another_day_or_no_state_holds_nothing(self) -> None:
|
||||||
"""A budget from another day, or none at all, holds nothing."""
|
"""A budget from another day, or none at all, holds nothing."""
|
||||||
stored = PlaytimeState(day_key="2026-07-26", shadow_budget_seconds=HOUR)
|
stored = PlaytimeState(
|
||||||
|
day_key="2026-07-26", shadow=ShadowLedger(budget_seconds=HOUR)
|
||||||
|
)
|
||||||
assert held_shadow_today(stored, _NOW) == 0.0
|
assert held_shadow_today(stored, _NOW) == 0.0
|
||||||
assert held_shadow_today(None, _NOW) == 0.0
|
assert held_shadow_today(None, _NOW) == 0.0
|
||||||
|
|
||||||
@ -135,9 +140,9 @@ class TestShadowTick:
|
|||||||
state = load_state(demo=False)
|
state = load_state(demo=False)
|
||||||
assert state is not None
|
assert state is not None
|
||||||
assert (state.seconds, state.per_game) == (3.0, {"app:440": 3.0})
|
assert (state.seconds, state.per_game) == (3.0, {"app:440": 3.0})
|
||||||
assert state.shadow_seconds == 3.0
|
assert state.shadow.seconds == 3.0
|
||||||
assert state.shadow_per_source == {"app:440": 3.0}
|
assert state.shadow.per_source == {"app:440": 3.0}
|
||||||
assert state.shadow_budget_seconds > 0.0
|
assert state.shadow.budget_seconds > 0.0
|
||||||
|
|
||||||
def test_no_game_and_no_watcher_fails_closed(self) -> None:
|
def test_no_game_and_no_watcher_fails_closed(self) -> None:
|
||||||
"""With no game and no watcher the shadow bills the fail-closed key."""
|
"""With no game and no watcher the shadow bills the fail-closed key."""
|
||||||
@ -145,15 +150,15 @@ class TestShadowTick:
|
|||||||
state = load_state(demo=False)
|
state = load_state(demo=False)
|
||||||
assert state is not None
|
assert state is not None
|
||||||
assert state.seconds == 0.0
|
assert state.seconds == 0.0
|
||||||
assert state.shadow_per_source == {_shadow.FAILCLOSED_KEY: 3.0}
|
assert state.shadow.per_source == {_shadow.FAILCLOSED_KEY: 3.0}
|
||||||
|
|
||||||
def test_no_shadow_under_a_total_block(self) -> None:
|
def test_no_shadow_under_a_total_block(self) -> None:
|
||||||
"""A total block bills no shadow seconds but keeps the budget."""
|
"""A total block bills no shadow seconds but keeps the budget."""
|
||||||
self._tick({}, total_block=True)
|
self._tick({}, total_block=True)
|
||||||
state = load_state(demo=False)
|
state = load_state(demo=False)
|
||||||
assert state is not None
|
assert state is not None
|
||||||
assert state.shadow_seconds == 0.0
|
assert state.shadow.seconds == 0.0
|
||||||
assert state.shadow_budget_seconds > 0.0
|
assert state.shadow.budget_seconds > 0.0
|
||||||
|
|
||||||
def test_the_session_journals_the_shadow_verdict(self) -> None:
|
def test_the_session_journals_the_shadow_verdict(self) -> None:
|
||||||
"""The tick journals the shadow verdict through the session."""
|
"""The tick journals the shadow verdict through the session."""
|
||||||
@ -183,10 +188,12 @@ class TestShadowViews:
|
|||||||
stored = PlaytimeState(
|
stored = PlaytimeState(
|
||||||
day_key=_TODAY,
|
day_key=_TODAY,
|
||||||
seconds=10.0,
|
seconds=10.0,
|
||||||
shadow_seconds=40.0,
|
shadow=ShadowLedger(
|
||||||
shadow_budget_seconds=100.0,
|
seconds=40.0,
|
||||||
shadow_per_source={"app:440": 40.0},
|
budget_seconds=100.0,
|
||||||
shadow_paused_seconds=5.0,
|
per_source={"app:440": 40.0},
|
||||||
|
paused_seconds=5.0,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
with (
|
with (
|
||||||
patch.object(budget_view, "load_state", return_value=stored),
|
patch.object(budget_view, "load_state", return_value=stored),
|
||||||
@ -204,7 +211,7 @@ class TestShadowViews:
|
|||||||
|
|
||||||
def test_would_block_at_zero(self) -> None:
|
def test_would_block_at_zero(self) -> None:
|
||||||
"""A spent shadow budget reports would_block with zero remaining."""
|
"""A spent shadow budget reports would_block with zero remaining."""
|
||||||
stored = PlaytimeState(shadow_seconds=100.0, shadow_budget_seconds=100.0)
|
stored = PlaytimeState(shadow=ShadowLedger(seconds=100.0, budget_seconds=100.0))
|
||||||
shadow = budget_view.build_today(stored, rules_for(Config(), demo=True))
|
shadow = budget_view.build_today(stored, rules_for(Config(), demo=True))
|
||||||
assert shadow["shadow"]["would_block"] is True
|
assert shadow["shadow"]["would_block"] is True
|
||||||
assert shadow["shadow"]["seconds_remaining"] == 0.0
|
assert shadow["shadow"]["seconds_remaining"] == 0.0
|
||||||
|
|||||||
@ -80,6 +80,16 @@ def test_a_successful_pause_check_still_pauses() -> None:
|
|||||||
assert observe_shadow({}, stamp=T0) == ShadowVerdict("i3lock", ())
|
assert observe_shadow({}, stamp=T0) == ShadowVerdict("i3lock", ())
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_programming_bug_is_loud() -> None:
|
||||||
|
"""An error outside FAIL_SAFE_ERRORS reaches the caller."""
|
||||||
|
with (
|
||||||
|
patch.object(_shadow, "paused_by", return_value=None),
|
||||||
|
patch.object(_shadow, "read_now", side_effect=AttributeError("bug")),
|
||||||
|
pytest.raises(AttributeError, match="bug"),
|
||||||
|
):
|
||||||
|
observe_shadow({}, stamp=T0)
|
||||||
|
|
||||||
|
|
||||||
def _warnings(caplog: pytest.LogCaptureFixture) -> list[str]:
|
def _warnings(caplog: pytest.LogCaptureFixture) -> list[str]:
|
||||||
return [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]
|
return [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]
|
||||||
|
|
||||||
@ -137,7 +147,7 @@ def test_tick_completes_and_enforced_count_is_untouched(
|
|||||||
state = load_state(demo=False)
|
state = load_state(demo=False)
|
||||||
assert state.seconds == seconds
|
assert state.seconds == seconds
|
||||||
assert state.last_tick_at == T0
|
assert state.last_tick_at == T0
|
||||||
assert state.shadow_per_source == {shadow: 3.0}
|
assert state.shadow.per_source == {shadow: 3.0}
|
||||||
|
|
||||||
|
|
||||||
def test_errors_older_than_the_window_are_forgotten() -> None:
|
def test_errors_older_than_the_window_are_forgotten() -> None:
|
||||||
|
|||||||
@ -7,16 +7,19 @@ import json
|
|||||||
from steam_backlog_enforcer import _playtime_log as log_mod
|
from steam_backlog_enforcer import _playtime_log as log_mod
|
||||||
from steam_backlog_enforcer._budget_log_tail import last_verdict
|
from steam_backlog_enforcer._budget_log_tail import last_verdict
|
||||||
from steam_backlog_enforcer._playtime_log import BudgetLog
|
from steam_backlog_enforcer._playtime_log import BudgetLog
|
||||||
|
from steam_backlog_enforcer._playtime_record import ShadowLedger
|
||||||
from steam_backlog_enforcer._playtime_state import PlaytimeState
|
from steam_backlog_enforcer._playtime_state import PlaytimeState
|
||||||
from steam_backlog_enforcer._shadow import ShadowVerdict
|
from steam_backlog_enforcer._shadow import ShadowVerdict
|
||||||
from steam_backlog_enforcer._shadow_log import EVENT_SHADOW_CHANGE, ShadowJournal
|
from steam_backlog_enforcer._shadow_log import EVENT_SHADOW_CHANGE, ShadowJournal
|
||||||
|
|
||||||
_STATE = PlaytimeState(
|
_STATE = PlaytimeState(
|
||||||
day_key="2026-10-19",
|
day_key="2026-10-19",
|
||||||
shadow_seconds=30.0,
|
shadow=ShadowLedger(
|
||||||
shadow_budget_seconds=36000.0,
|
seconds=30.0,
|
||||||
shadow_per_source={"app:440": 30.0},
|
budget_seconds=36000.0,
|
||||||
shadow_paused_seconds=6.0,
|
per_source={"app:440": 30.0},
|
||||||
|
paused_seconds=6.0,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -151,7 +151,7 @@ class TestWorkoutLogPath:
|
|||||||
def test_expands_the_home_directory(self) -> None:
|
def test_expands_the_home_directory(self) -> None:
|
||||||
"""A ~ in the configured path expands to the home directory."""
|
"""A ~ in the configured path expands to the home directory."""
|
||||||
config = Config()
|
config = Config()
|
||||||
config.workout_log_path = "~/locker/log.json"
|
config.earn.workout_log_path = "~/locker/log.json"
|
||||||
assert workout_log_path(config) == Path.home() / "locker" / "log.json"
|
assert workout_log_path(config) == Path.home() / "locker" / "log.json"
|
||||||
|
|
||||||
def test_default_points_at_screen_locker(self) -> None:
|
def test_default_points_at_screen_locker(self) -> None:
|
||||||
|
|||||||
@ -68,12 +68,12 @@ class TestBuildGames:
|
|||||||
rows = self._run([_gi(app_id=1, completionist_hours=0.0)], set(), raw, proton)
|
rows = self._run([_gi(app_id=1, completionist_hours=0.0)], set(), raw, proton)
|
||||||
assert len(rows) == 1
|
assert len(rows) == 1
|
||||||
row = rows[0]
|
row = rows[0]
|
||||||
assert row.rush_hours == 9.0
|
assert row.hltb.rush_hours == 9.0
|
||||||
assert row.leisure_hours == 22.0
|
assert row.hltb.leisure_hours == 22.0
|
||||||
assert row.worst_hours == 22.0 # max(cache 18, leisure 22)
|
assert row.hltb.worst_hours == 22.0 # max(cache 18, leisure 22)
|
||||||
assert row.count_comp == 30
|
assert row.hltb.count_comp == 30
|
||||||
assert row.comp_100_count == 7
|
assert row.hltb.comp_100_count == 7
|
||||||
assert row.hltb_game_id == 555
|
assert row.hltb.hltb_game_id == 555
|
||||||
assert row.protondb_tier == "platinum"
|
assert row.protondb_tier == "platinum"
|
||||||
assert row.protondb_trending_tier == "gold"
|
assert row.protondb_trending_tier == "gold"
|
||||||
|
|
||||||
@ -82,9 +82,9 @@ class TestBuildGames:
|
|||||||
rows = self._run([_gi(app_id=1, completionist_hours=12.0)], set())
|
rows = self._run([_gi(app_id=1, completionist_hours=12.0)], set())
|
||||||
assert len(rows) == 1
|
assert len(rows) == 1
|
||||||
row = rows[0]
|
row = rows[0]
|
||||||
assert row.rush_hours == -1
|
assert row.hltb.rush_hours == -1
|
||||||
assert row.leisure_hours == -1
|
assert row.hltb.leisure_hours == -1
|
||||||
assert row.worst_hours == 12.0 # completionist only
|
assert row.hltb.worst_hours == 12.0 # completionist only
|
||||||
assert row.protondb_tier == "" # no protondb entry
|
assert row.protondb_tier == "" # no protondb entry
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -2,13 +2,17 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import replace
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
from steam_backlog_enforcer._web_dataset import (
|
from steam_backlog_enforcer._web_dataset import (
|
||||||
|
WebDataset,
|
||||||
|
WebGame,
|
||||||
build_web_dataset,
|
build_web_dataset,
|
||||||
dataset_to_payload,
|
dataset_to_payload,
|
||||||
)
|
)
|
||||||
from steam_backlog_enforcer.config import State
|
from steam_backlog_enforcer.config import State
|
||||||
|
from steam_backlog_enforcer.tests._web_dataset_factories import _wg
|
||||||
|
|
||||||
_PKG = "steam_backlog_enforcer._web_games"
|
_PKG = "steam_backlog_enforcer._web_games"
|
||||||
# build_web_dataset itself did not move.
|
# build_web_dataset itself did not move.
|
||||||
@ -36,3 +40,34 @@ class TestDatasetToPayload:
|
|||||||
}
|
}
|
||||||
assert isinstance(payload["games"], list)
|
assert isinstance(payload["games"], list)
|
||||||
assert isinstance(payload["state"], dict)
|
assert isinstance(payload["state"], dict)
|
||||||
|
|
||||||
|
def test_game_rows_are_served_flat(self) -> None:
|
||||||
|
"""The HLTB group is inlined: the browser's row keys do not change."""
|
||||||
|
dataset = build_web_dataset_with([_wg(rush_hours=3.0)])
|
||||||
|
row = dataset_to_payload(dataset)["games"][0]
|
||||||
|
assert list(row) == [
|
||||||
|
"app_id",
|
||||||
|
"name",
|
||||||
|
"completion_pct",
|
||||||
|
"playtime_minutes",
|
||||||
|
"rush_hours",
|
||||||
|
"leisure_hours",
|
||||||
|
"worst_hours",
|
||||||
|
"count_comp",
|
||||||
|
"comp_100_count",
|
||||||
|
"hltb_game_id",
|
||||||
|
"protondb_tier",
|
||||||
|
"protondb_trending_tier",
|
||||||
|
"protondb_score",
|
||||||
|
]
|
||||||
|
assert row["rush_hours"] == 3.0
|
||||||
|
|
||||||
|
|
||||||
|
def build_web_dataset_with(games: list[WebGame]) -> WebDataset:
|
||||||
|
"""An otherwise empty dataset carrying *games*."""
|
||||||
|
with (
|
||||||
|
patch(f"{_DATASET_PKG}.load_snapshot", return_value=None),
|
||||||
|
patch(f"{_PKG}._read_raw_cache", return_value={}),
|
||||||
|
patch(f"{_PKG}._load_cache", return_value={}),
|
||||||
|
):
|
||||||
|
return replace(build_web_dataset(State()), games=games)
|
||||||
|
|||||||
56
steam_backlog_enforcer/tests/test_web_server_fail_safe.py
Normal file
56
steam_backlog_enforcer/tests/test_web_server_fail_safe.py
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
"""A route bug outside FAIL_SAFE_ERRORS is loud, and the server keeps serving."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from http.client import HTTPConnection, RemoteDisconnected
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from steam_backlog_enforcer.tests._web_process_state import (
|
||||||
|
clean_process_state,
|
||||||
|
running_server,
|
||||||
|
)
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Iterator
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._web_io import Reply, Request
|
||||||
|
|
||||||
|
_PKG = "steam_backlog_enforcer._web_server"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _clean_process_state() -> Iterator[None]:
|
||||||
|
"""No retiring flag, and never "stale"."""
|
||||||
|
yield from clean_process_state()
|
||||||
|
|
||||||
|
|
||||||
|
def _get(port: int, path: str) -> int:
|
||||||
|
"""One GET; the status, or ``-1`` if the server hung up without one."""
|
||||||
|
conn = HTTPConnection("127.0.0.1", port, timeout=5)
|
||||||
|
try:
|
||||||
|
conn.request("GET", path)
|
||||||
|
return conn.getresponse().status
|
||||||
|
except RemoteDisconnected:
|
||||||
|
return -1
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_bug_drops_the_request_and_the_server_survives() -> None:
|
||||||
|
"""The buggy request gets no answer; the next request is served."""
|
||||||
|
|
||||||
|
def route(_request: Request) -> Reply:
|
||||||
|
msg = "bug"
|
||||||
|
raise AttributeError(msg)
|
||||||
|
|
||||||
|
with running_server() as server:
|
||||||
|
with (
|
||||||
|
patch(f"{_PKG}.resolve", return_value=(route, ())),
|
||||||
|
patch.object(server, "handle_error") as handle_error,
|
||||||
|
):
|
||||||
|
assert _get(server.port, "/api/budget") == -1
|
||||||
|
handle_error.assert_called_once()
|
||||||
|
assert _get(server.port, "/api/jobs") == 200
|
||||||
@ -2,10 +2,8 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from contextlib import contextmanager
|
|
||||||
from http.client import HTTPConnection
|
from http.client import HTTPConnection
|
||||||
import json
|
import json
|
||||||
import threading
|
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
@ -16,7 +14,10 @@ from steam_backlog_enforcer._web_io import Reply, Request, ok
|
|||||||
from steam_backlog_enforcer._web_server import _STALE_MSG
|
from steam_backlog_enforcer._web_server import _STALE_MSG
|
||||||
from steam_backlog_enforcer.jobs._daemon_jobs import DaemonOutcome, record_daemon_job
|
from steam_backlog_enforcer.jobs._daemon_jobs import DaemonOutcome, record_daemon_job
|
||||||
from steam_backlog_enforcer.jobs._events import now_iso
|
from steam_backlog_enforcer.jobs._events import now_iso
|
||||||
from steam_backlog_enforcer.tests._web_process_state import clean_process_state
|
from steam_backlog_enforcer.tests._web_process_state import (
|
||||||
|
clean_process_state,
|
||||||
|
running_server,
|
||||||
|
)
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from collections.abc import Iterator
|
from collections.abc import Iterator
|
||||||
@ -31,20 +32,7 @@ def _clean_process_state() -> Iterator[None]:
|
|||||||
yield from clean_process_state()
|
yield from clean_process_state()
|
||||||
|
|
||||||
|
|
||||||
@contextmanager
|
_running = running_server
|
||||||
def _running() -> Iterator[_web_server.WebServer]:
|
|
||||||
"""Serve on an ephemeral loopback port in a thread."""
|
|
||||||
server = _web_server.create_server("127.0.0.1", 0)
|
|
||||||
thread = threading.Thread(
|
|
||||||
target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True
|
|
||||||
)
|
|
||||||
thread.start()
|
|
||||||
try:
|
|
||||||
yield server
|
|
||||||
finally:
|
|
||||||
server.shutdown()
|
|
||||||
server.server_close()
|
|
||||||
thread.join(timeout=2)
|
|
||||||
|
|
||||||
|
|
||||||
def _auth(server: _web_server.WebServer) -> dict[str, str]:
|
def _auth(server: _web_server.WebServer) -> dict[str, str]:
|
||||||
|
|||||||
@ -52,9 +52,9 @@ def _config(**over: object) -> Config:
|
|||||||
A Config instance; never loaded from or saved to disk.
|
A Config instance; never loaded from or saved to disk.
|
||||||
"""
|
"""
|
||||||
config = Config()
|
config = Config()
|
||||||
config.workout_status_url = "http://127.0.0.1:8770/api/status"
|
config.earn.workout_status_url = "http://127.0.0.1:8770/api/status"
|
||||||
for key, value in over.items():
|
for key, value in over.items():
|
||||||
setattr(config, key, value)
|
setattr(config.earn, key, value)
|
||||||
return config
|
return config
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -20,7 +20,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@kuhyx/web-ui": "github:kuhyx/utils#web_ui-v0.5.0&path:/web_ui",
|
"@kuhyx/web-ui": "github:kuhyx/utils#web_ui-v0.5.0&path:/web_ui",
|
||||||
"astro": "7.4.8"
|
"astro": "7.4.10"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@astrojs/check": "0.9.12",
|
"@astrojs/check": "0.9.12",
|
||||||
|
|||||||
@ -172,10 +172,10 @@ importers:
|
|||||||
dependencies:
|
dependencies:
|
||||||
'@kuhyx/web-ui':
|
'@kuhyx/web-ui':
|
||||||
specifier: github:kuhyx/utils#web_ui-v0.5.0&path:/web_ui
|
specifier: github:kuhyx/utils#web_ui-v0.5.0&path:/web_ui
|
||||||
version: https://codeload.github.com/kuhyx/utils/tar.gz/decf5824e609b099f9455be93c4d09b4c1fd6cae#path:/web_ui(astro@7.4.8(@types/node@26.6.6)(yaml@2.9.1))
|
version: https://codeload.github.com/kuhyx/utils/tar.gz/decf5824e609b099f9455be93c4d09b4c1fd6cae#path:/web_ui(astro@7.4.10(@types/node@26.6.6)(yaml@2.9.1))
|
||||||
astro:
|
astro:
|
||||||
specifier: 7.4.8
|
specifier: 7.4.10
|
||||||
version: 7.4.8(@types/node@26.6.6)(yaml@2.9.1)
|
version: 7.4.10(@types/node@26.6.6)(yaml@2.9.1)
|
||||||
devDependencies:
|
devDependencies:
|
||||||
'@astrojs/check':
|
'@astrojs/check':
|
||||||
specifier: 0.9.12
|
specifier: 0.9.12
|
||||||
@ -306,8 +306,8 @@ packages:
|
|||||||
resolution: {integrity: sha512-IvwYLB8t1M86rKO4oPdBi9GP4gzXcgrVlNgocjwos1jeeUuEIV8d9Crn1PvYD/5IKteWOxpIHomf7e8iYlkE+Q==}
|
resolution: {integrity: sha512-IvwYLB8t1M86rKO4oPdBi9GP4gzXcgrVlNgocjwos1jeeUuEIV8d9Crn1PvYD/5IKteWOxpIHomf7e8iYlkE+Q==}
|
||||||
engines: {node: '>=22.12.0'}
|
engines: {node: '>=22.12.0'}
|
||||||
|
|
||||||
'@astrojs/internal-helpers@0.13.1':
|
'@astrojs/internal-helpers@0.13.2':
|
||||||
resolution: {integrity: sha512-LgGLGzoC0wCT3mjDYrxz+hct/tws0enpWsLJW3bswHR3PKgusp/H9xRIT8rTdsyvLM0TcRhhvRL30J2oaZNcqA==}
|
resolution: {integrity: sha512-SWiNS+OMrhwWYzJENTekHUyUCMKB+tdU6D4v1ZNIU1ZHh2mScQ8WIs0J6AJ8KPXkIrs9+EZU7Rm2CstfThyVnw==}
|
||||||
|
|
||||||
'@astrojs/language-server@2.17.3':
|
'@astrojs/language-server@2.17.3':
|
||||||
resolution: {integrity: sha512-QIAFu1e/4quJMTPdmBOm+ZPXc5NDGZE4/YQjgR3EgjhGLl/tdidaWJDr5WmO2lesVc+BW1qN/xNBURmuePDG2A==}
|
resolution: {integrity: sha512-QIAFu1e/4quJMTPdmBOm+ZPXc5NDGZE4/YQjgR3EgjhGLl/tdidaWJDr5WmO2lesVc+BW1qN/xNBURmuePDG2A==}
|
||||||
@ -321,17 +321,25 @@ packages:
|
|||||||
prettier-plugin-astro:
|
prettier-plugin-astro:
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
'@astrojs/markdown-satteri@0.4.7':
|
'@astrojs/markdown-satteri@0.4.8':
|
||||||
resolution: {integrity: sha512-MZvnec/898GGGHQZfkArVbkdZmL1imjIM8RWkmzbAmse737zr8D9inUjFQ5eLBXV3vPobOUs/ZRV/D6Po/bVDg==}
|
resolution: {integrity: sha512-IKAfvJGJ/RhXzvRkZ89kXp5woRTlRm0LVqhu8HOZAW3FAdWyZY9fYKcoVc472CJAsq8JjJjQzRkW6uaUkyufSw==}
|
||||||
|
|
||||||
'@astrojs/prism@4.1.2':
|
'@astrojs/prism@4.1.2':
|
||||||
resolution: {integrity: sha512-jMrUEpFDarDO1KWPvVc9eSa8DSfwBlwEOHwX+8zvZQpiqXRGDxFnOXHsYqV6DP7w+0qIgTr98gS1GdQlm8ypWg==}
|
resolution: {integrity: sha512-jMrUEpFDarDO1KWPvVc9eSa8DSfwBlwEOHwX+8zvZQpiqXRGDxFnOXHsYqV6DP7w+0qIgTr98gS1GdQlm8ypWg==}
|
||||||
engines: {node: '>=22.23.4'}
|
engines: {node: '>=22.23.4'}
|
||||||
|
|
||||||
|
'@astrojs/runtime@0.1.0':
|
||||||
|
resolution: {integrity: sha512-Ips60LS4g0jEwOq7qOZqBhVl/6/nUDsk83bFbPBDYwtSfIiknaN48aSD+ycnwhBpUvbxQMQHv1ZotrCJFsJzPw==}
|
||||||
|
|
||||||
'@astrojs/telemetry@3.4.2':
|
'@astrojs/telemetry@3.4.2':
|
||||||
resolution: {integrity: sha512-2JOMRUxJrBSfiVDfeKLv1wBmvSIx1Y6u2YEO8awZ9qSq3u/rNAiUyFdOYi8dHv91kHrmYEQX7pRDw0J4xyj3UA==}
|
resolution: {integrity: sha512-2JOMRUxJrBSfiVDfeKLv1wBmvSIx1Y6u2YEO8awZ9qSq3u/rNAiUyFdOYi8dHv91kHrmYEQX7pRDw0J4xyj3UA==}
|
||||||
engines: {node: '>=22.23.4'}
|
engines: {node: '>=22.23.4'}
|
||||||
|
|
||||||
|
'@astrojs/vite-plugin-astro@0.1.1':
|
||||||
|
resolution: {integrity: sha512-JiRu3n9jWRFwSuarVKFYFQEqxAuy+k5Hqyr0IMmafjpd75tiPyQ4W9MTSrnjsqNs0SYcS6vGNXZ5CTwrXNSglQ==}
|
||||||
|
peerDependencies:
|
||||||
|
vite: ^8.3.3
|
||||||
|
|
||||||
'@astrojs/yaml2ts@0.2.4':
|
'@astrojs/yaml2ts@0.2.4':
|
||||||
resolution: {integrity: sha512-8oddpOae35pJsXPQXhTkM0ypfKPskVsh2bCxRtbf7e+/Epw2nReakFYpLKjZMEr75CsoF203PMnCocpfz0s69A==}
|
resolution: {integrity: sha512-8oddpOae35pJsXPQXhTkM0ypfKPskVsh2bCxRtbf7e+/Epw2nReakFYpLKjZMEr75CsoF203PMnCocpfz0s69A==}
|
||||||
|
|
||||||
@ -1157,8 +1165,8 @@ packages:
|
|||||||
resolution: {integrity: sha512-WavQUarfgwSbpCq4xsdcIBdX5KArfI2d6DD8EIloJIMthnB1508iNpx4C77EhUyMd03LpEt8HAPzwF/cG0V39g==}
|
resolution: {integrity: sha512-WavQUarfgwSbpCq4xsdcIBdX5KArfI2d6DD8EIloJIMthnB1508iNpx4C77EhUyMd03LpEt8HAPzwF/cG0V39g==}
|
||||||
engines: {node: ^22.22.3 || ^24.16.0 || >=26.3.0}
|
engines: {node: ^22.22.3 || ^24.16.0 || >=26.3.0}
|
||||||
|
|
||||||
astro@7.4.8:
|
astro@7.4.10:
|
||||||
resolution: {integrity: sha512-xBcOeUvOQGPDKeHiIRJCKNZStf+TyPEJ2kHrUBKpVEyEdhhPfHd0T9GP8NVvaA3I7aKPn6SGy8xEcvWPym4GsA==}
|
resolution: {integrity: sha512-NQfkQCCGZz3pzUy04tN3iRehKZq0S+FcjnrBwLTmVNZC6+BUAzMYxmdzLpf6Dovb6zVjMQJeMziKI4hjX3BQlw==}
|
||||||
engines: {node: '>=22.23.4', npm: '>=9.6.5', pnpm: '>=7.1.0'}
|
engines: {node: '>=22.23.4', npm: '>=9.6.5', pnpm: '>=7.1.0'}
|
||||||
hasBin: true
|
hasBin: true
|
||||||
peerDependencies:
|
peerDependencies:
|
||||||
@ -2612,7 +2620,7 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
'@astrojs/compiler-binding': 0.5.2
|
'@astrojs/compiler-binding': 0.5.2
|
||||||
|
|
||||||
'@astrojs/internal-helpers@0.13.1':
|
'@astrojs/internal-helpers@0.13.2':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@types/hast': 3.0.5
|
'@types/hast': 3.0.5
|
||||||
'@types/mdast': 4.0.4
|
'@types/mdast': 4.0.4
|
||||||
@ -2648,9 +2656,9 @@ snapshots:
|
|||||||
- '@emnapi/runtime'
|
- '@emnapi/runtime'
|
||||||
- typescript
|
- typescript
|
||||||
|
|
||||||
'@astrojs/markdown-satteri@0.4.7':
|
'@astrojs/markdown-satteri@0.4.8':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@astrojs/internal-helpers': 0.13.1
|
'@astrojs/internal-helpers': 0.13.2
|
||||||
'@astrojs/prism': 4.1.2
|
'@astrojs/prism': 4.1.2
|
||||||
github-slugger: 2.0.0
|
github-slugger: 2.0.0
|
||||||
satteri: 0.11.6
|
satteri: 0.11.6
|
||||||
@ -2659,6 +2667,11 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
prismjs: 1.30.0
|
prismjs: 1.30.0
|
||||||
|
|
||||||
|
'@astrojs/runtime@0.1.0':
|
||||||
|
dependencies:
|
||||||
|
'@oslojs/encoding': 1.1.0
|
||||||
|
clsx: 2.1.1
|
||||||
|
|
||||||
'@astrojs/telemetry@3.4.2':
|
'@astrojs/telemetry@3.4.2':
|
||||||
dependencies:
|
dependencies:
|
||||||
ci-info: 4.4.0
|
ci-info: 4.4.0
|
||||||
@ -2666,6 +2679,19 @@ snapshots:
|
|||||||
is-docker: 4.0.0
|
is-docker: 4.0.0
|
||||||
package-manager-detector: 1.9.0
|
package-manager-detector: 1.9.0
|
||||||
|
|
||||||
|
'@astrojs/vite-plugin-astro@0.1.1(vite@8.3.7(@types/node@26.6.6)(yaml@2.9.1))':
|
||||||
|
dependencies:
|
||||||
|
'@astrojs/compiler-rs': 0.5.2
|
||||||
|
'@astrojs/internal-helpers': 0.13.2
|
||||||
|
'@astrojs/runtime': 0.1.0
|
||||||
|
common-ancestor-path: 2.0.0
|
||||||
|
devalue: 6.0.3
|
||||||
|
magic-string: 1.4.5
|
||||||
|
rolldown: 1.2.18
|
||||||
|
smol-toml: 1.9.1
|
||||||
|
vite: 8.3.7(@types/node@26.6.6)(yaml@2.9.1)
|
||||||
|
zod: 4.6.7
|
||||||
|
|
||||||
'@astrojs/yaml2ts@0.2.4':
|
'@astrojs/yaml2ts@0.2.4':
|
||||||
dependencies:
|
dependencies:
|
||||||
yaml: 2.9.1
|
yaml: 2.9.1
|
||||||
@ -2970,9 +2996,9 @@ snapshots:
|
|||||||
|
|
||||||
'@keyv/serialize@1.1.1': {}
|
'@keyv/serialize@1.1.1': {}
|
||||||
|
|
||||||
'@kuhyx/web-ui@https://codeload.github.com/kuhyx/utils/tar.gz/decf5824e609b099f9455be93c4d09b4c1fd6cae#path:/web_ui(astro@7.4.8(@types/node@26.6.6)(yaml@2.9.1))':
|
'@kuhyx/web-ui@https://codeload.github.com/kuhyx/utils/tar.gz/decf5824e609b099f9455be93c4d09b4c1fd6cae#path:/web_ui(astro@7.4.10(@types/node@26.6.6)(yaml@2.9.1))':
|
||||||
dependencies:
|
dependencies:
|
||||||
astro: 7.4.8(@types/node@26.6.6)(yaml@2.9.1)
|
astro: 7.4.10(@types/node@26.6.6)(yaml@2.9.1)
|
||||||
|
|
||||||
'@napi-rs/wasm-runtime@1.2.4(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)':
|
'@napi-rs/wasm-runtime@1.2.4(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3)':
|
||||||
dependencies:
|
dependencies:
|
||||||
@ -3412,12 +3438,14 @@ snapshots:
|
|||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- supports-color
|
- supports-color
|
||||||
|
|
||||||
astro@7.4.8(@types/node@26.6.6)(yaml@2.9.1):
|
astro@7.4.10(@types/node@26.6.6)(yaml@2.9.1):
|
||||||
dependencies:
|
dependencies:
|
||||||
'@astrojs/compiler-rs': 0.5.2
|
'@astrojs/compiler-rs': 0.5.2
|
||||||
'@astrojs/internal-helpers': 0.13.1
|
'@astrojs/internal-helpers': 0.13.2
|
||||||
'@astrojs/markdown-satteri': 0.4.7
|
'@astrojs/markdown-satteri': 0.4.8
|
||||||
|
'@astrojs/runtime': 0.1.0
|
||||||
'@astrojs/telemetry': 3.4.2
|
'@astrojs/telemetry': 3.4.2
|
||||||
|
'@astrojs/vite-plugin-astro': 0.1.1(vite@8.3.7(@types/node@26.6.6)(yaml@2.9.1))
|
||||||
'@capsizecss/unpack': 4.0.1
|
'@capsizecss/unpack': 4.0.1
|
||||||
'@clack/prompts': 1.8.1
|
'@clack/prompts': 1.8.1
|
||||||
'@oslojs/encoding': 1.1.0
|
'@oslojs/encoding': 1.1.0
|
||||||
@ -3425,8 +3453,6 @@ snapshots:
|
|||||||
aria-query: 5.3.2
|
aria-query: 5.3.2
|
||||||
axobject-query: 4.1.0
|
axobject-query: 4.1.0
|
||||||
ci-info: 4.4.0
|
ci-info: 4.4.0
|
||||||
clsx: 2.1.1
|
|
||||||
common-ancestor-path: 2.0.0
|
|
||||||
cookie: 2.0.2
|
cookie: 2.0.2
|
||||||
devalue: 6.0.3
|
devalue: 6.0.3
|
||||||
diff: 9.0.0
|
diff: 9.0.0
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user