mirror of
https://github.com/kuhyx/steam-backlog-enforcer.git
synced 2026-11-28 00:29:05 +01:00
Research window: keep Steam dir, extend once
kuhy 2026-11-11, multi-day research without re-setup. W1: once a window was used in a lock, the block's purge spares ~/.local/share/Steam (Librarian's install and local saves) for the rest of the lock; ~/steam, ~/.steam and the rest still go. The package stays removed, hosts/iptables are re-applied, and since the kept install could otherwise be launched without the package, every Steam game is killed on sight. A record that cannot be read also keeps the folder (an irreversible delete never rests on unknown state); the block itself stays fully applied. W2: the 48 h cap is gone; --until is bounded by the lock's end. An open window may be extended ONCE, to the lock end at most, never shortened, never reopened after it ended. The extension is a separate extended_until field beside until, so a daemon still on the previous code reads the original window instead of rejecting the record as corrupt (which would have purged the folder). Failure modes unchanged: missing/corrupt record = no window, and a corrupt one refuses a new window or extension. Checked: 3325 tests at 100% coverage; pylint 10/10 in parts; vmbox: extension accepted once, refused beyond the lock end, earlier or equal, second time and non-root; extended end honoured past the original end; at close the Steam dir and a save survive, ~/steam and ~/.steam go, a game started after close is killed; extension to exactly the lock end accepted. Not verified on the host. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WzxdWWzuCEg1m87jpKyRrw
This commit is contained in:
parent
c4938dd9ee
commit
87c6f200e3
@ -36,7 +36,7 @@ python -m python_pkg.steam_backlog_enforcer.main setup
|
|||||||
| `unblock [minutes]` | Unblock the store for a window (default 15, max 30); the daemon keeps it open and re-blocks after |
|
| `unblock [minutes]` | Unblock the store for a window (default 15, max 30); the daemon keeps it open and re-blocks after |
|
||||||
| `buy-dlc` | Same 15-minute store window, to buy a game or DLC |
|
| `buy-dlc` | Same 15-minute store window, to buy a game or DLC |
|
||||||
| `reset` | Reset all state |
|
| `reset` | Reset all state |
|
||||||
| `total-block-research --until T` | Root. One window per total block (at most 48 h): Steam and the store open, only Librarian may be played; the daemon re-applies the full block at `T` |
|
| `total-block-research --until T` | Root. One window per total block, up to its end, extendable once: Steam and the store open, only Librarian may be played; the daemon re-applies the full block at `T` and keeps `~/.local/share/Steam` |
|
||||||
| `installed` | List currently installed Steam games |
|
| `installed` | List currently installed Steam games |
|
||||||
| `uninstall` | Interactively uninstall non-assigned games |
|
| `uninstall` | Interactively uninstall non-assigned games |
|
||||||
| `setup` | First-time configuration |
|
| `setup` | First-time configuration |
|
||||||
|
|||||||
@ -2,10 +2,11 @@
|
|||||||
|
|
||||||
kuhy 2026-11-11: game-design research needs "Librarian: Tidy Up the Arcane
|
kuhy 2026-11-11: game-design research needs "Librarian: Tidy Up the Arcane
|
||||||
Library" actually played during a 6-day total block. This command opens ONE
|
Library" actually played during a 6-day total block. This command opens ONE
|
||||||
window per lock, ending at ``--until`` (at most 48 h away, never past the
|
window per lock, ending at ``--until`` (never past the lock's end). While it is
|
||||||
lock's end, never extended by a rerun). It only validates and records the
|
open, one rerun with a later ``--until`` extends it (again to the lock's end at
|
||||||
window; the enforcer daemon opens Steam within a pass and re-applies the full
|
most); nothing shortens it. It only validates and records the window; the
|
||||||
block at the deadline (:mod:`steam_backlog_enforcer._research_tick`).
|
enforcer daemon opens Steam within a pass and re-applies the full block at the
|
||||||
|
deadline (:mod:`steam_backlog_enforcer._research_tick`).
|
||||||
|
|
||||||
Root-only: the record sits in a root-only state directory. The lock and its
|
Root-only: the record sits in a root-only state directory. The lock and its
|
||||||
end date are untouched, so this can never shorten or end a total block.
|
end date are untouched, so this can never shorten or end a total block.
|
||||||
@ -22,7 +23,7 @@ from steam_backlog_enforcer._echo import _echo
|
|||||||
_USAGE = (
|
_USAGE = (
|
||||||
"Usage: total-block-research --until <ISO time, local unless it has an offset>"
|
"Usage: total-block-research --until <ISO time, local unless it has an offset>"
|
||||||
"\n e.g. total-block-research --until 2026-11-13T00:00"
|
"\n e.g. total-block-research --until 2026-11-13T00:00"
|
||||||
"\n One window per total block, at most 48 h, Librarian only."
|
"\n One window per total block, up to its end, extendable once. Librarian only."
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@ -63,9 +64,16 @@ def cmd_total_block_research(args: list[str]) -> int:
|
|||||||
except window.ResearchRefusedError as exc:
|
except window.ResearchRefusedError as exc:
|
||||||
_echo(f"Refused: {exc}")
|
_echo(f"Refused: {exc}")
|
||||||
return 1
|
return 1
|
||||||
ends = datetime.fromtimestamp(record.until).astimezone()
|
ends = datetime.fromtimestamp(record.ends_at).astimezone()
|
||||||
_echo(f"Research window recorded until {ends:%Y-%m-%d %H:%M %Z}.")
|
extended = record.extended_until is not None
|
||||||
|
verb = "extended" if extended else "recorded"
|
||||||
|
_echo(f"Research window {verb} until {ends:%Y-%m-%d %H:%M %Z}.")
|
||||||
_echo(f"Only {window.LIBRARIAN_NAME} (AppID {window.LIBRARIAN_APP_ID}) may run.")
|
_echo(f"Only {window.LIBRARIAN_NAME} (AppID {window.LIBRARIAN_APP_ID}) may run.")
|
||||||
_echo("The enforcer opens Steam on its next pass and re-applies the full")
|
_echo("The enforcer opens Steam on its next pass and re-applies the full")
|
||||||
_echo("total block at the deadline. This window cannot be reopened or extended.")
|
_echo("total block at the deadline (the Steam folder is kept).")
|
||||||
|
_echo(
|
||||||
|
"That was the one extension; it is never reopened."
|
||||||
|
if extended
|
||||||
|
else "It is extendable once, never reopened."
|
||||||
|
)
|
||||||
return 0
|
return 0
|
||||||
|
|||||||
@ -41,9 +41,10 @@ _MANUAL_LOCK_EXEMPT_COMMANDS = frozenset(
|
|||||||
# Commands that remain usable while a total gaming block is active. Far
|
# Commands that remain usable while a total gaming block is active. Far
|
||||||
# stricter than _MANUAL_LOCK_EXEMPT_COMMANDS: no done/pick/reset/
|
# stricter than _MANUAL_LOCK_EXEMPT_COMMANDS: no done/pick/reset/
|
||||||
# add-exception - nothing here shortens or ends a total block. The one bounded
|
# add-exception - nothing here shortens or ends a total block. The one bounded
|
||||||
# opening is total-block-research: root-only, a single <= 48 h window per lock
|
# opening is total-block-research: root-only, a single window per lock that
|
||||||
# that only Librarian may use, recorded in a root-only state directory; the
|
# only Librarian may use (up to the lock's end, extendable once), recorded in a
|
||||||
# daemon re-applies the full block when it expires (the lock's end is fixed).
|
# root-only state directory; the daemon re-applies the full block when it
|
||||||
|
# expires. The lock and its end date are never touched.
|
||||||
#
|
#
|
||||||
# gaming-unblock is included because a playtime bind mount makes the total
|
# gaming-unblock is included because a playtime bind mount makes the total
|
||||||
# block's own `pacman -R steam` fail EBUSY - it must stay reachable exactly
|
# block's own `pacman -R steam` fail EBUSY - it must stay reachable exactly
|
||||||
|
|||||||
@ -6,6 +6,10 @@ so the unprivileged user can neither forge a window nor delete the used-up
|
|||||||
marker. It holds numbers and two latches only; no free text. Anything that
|
marker. It holds numbers and two latches only; no free text. Anything that
|
||||||
does not parse exactly, or that no legitimate open could have produced, is an
|
does not parse exactly, or that no legitimate open could have produced, is an
|
||||||
error: the caller treats that as "no window" (fail closed).
|
error: the caller treats that as "no window" (fail closed).
|
||||||
|
|
||||||
|
The one extension is a separate ``extended_until`` beside the original
|
||||||
|
``until`` (never an overwrite of it): a daemon still on the earlier code reads
|
||||||
|
the record as the original window instead of rejecting it as corrupt.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@ -18,7 +22,6 @@ from typing import Final
|
|||||||
|
|
||||||
from steam_backlog_enforcer.config import atomic_write
|
from steam_backlog_enforcer.config import atomic_write
|
||||||
|
|
||||||
MAX_WINDOW_SECONDS: Final = 48 * 3600.0
|
|
||||||
RESEARCH_FILE: Final = Path("/var/lib/steam-backlog-enforcer/total_block_research.json")
|
RESEARCH_FILE: Final = Path("/var/lib/steam-backlog-enforcer/total_block_research.json")
|
||||||
|
|
||||||
_NUMBER_KEYS: Final = ("lock_started_at", "lock_until", "opened_at", "until")
|
_NUMBER_KEYS: Final = ("lock_started_at", "lock_until", "opened_at", "until")
|
||||||
@ -41,10 +44,17 @@ class ResearchRecord:
|
|||||||
"""Latched once the deadline passed: a clock set back cannot reopen it."""
|
"""Latched once the deadline passed: a clock set back cannot reopen it."""
|
||||||
store_reblocked: bool = False
|
store_reblocked: bool = False
|
||||||
"""Latched once the normal store block is back after the window."""
|
"""Latched once the normal store block is back after the window."""
|
||||||
|
extended_until: float | None = None
|
||||||
|
"""The deadline after the window's single extension, if it was extended."""
|
||||||
|
|
||||||
|
@property
|
||||||
|
def ends_at(self) -> float:
|
||||||
|
"""The deadline in force: the extension if there is one, else ``until``."""
|
||||||
|
return self.until if self.extended_until is None else self.extended_until
|
||||||
|
|
||||||
def is_open(self, at: float) -> bool:
|
def is_open(self, at: float) -> bool:
|
||||||
"""Whether the window is open at *at* (epoch seconds)."""
|
"""Whether the window is open at *at* (epoch seconds)."""
|
||||||
return not self.closed and self.opened_at <= at < self.until
|
return not self.closed and self.opened_at <= at < self.ends_at
|
||||||
|
|
||||||
def to_json(self) -> str:
|
def to_json(self) -> str:
|
||||||
"""The record as the JSON text stored on disk."""
|
"""The record as the JSON text stored on disk."""
|
||||||
@ -68,6 +78,11 @@ def _number(data: dict[str, object], key: str) -> float:
|
|||||||
return number
|
return number
|
||||||
|
|
||||||
|
|
||||||
|
def _optional_number(data: dict[str, object], key: str) -> float | None:
|
||||||
|
"""A finite number, or None when the key is absent or null."""
|
||||||
|
return None if data.get(key) is None else _number(data, key)
|
||||||
|
|
||||||
|
|
||||||
def _flag(data: dict[str, object], key: str) -> bool:
|
def _flag(data: dict[str, object], key: str) -> bool:
|
||||||
"""A real boolean from *data*, False when absent."""
|
"""A real boolean from *data*, False when absent."""
|
||||||
value = data.get(key, False)
|
value = data.get(key, False)
|
||||||
@ -94,7 +109,8 @@ def parse_record(raw: str) -> ResearchRecord:
|
|||||||
raise ResearchStateError(msg)
|
raise ResearchStateError(msg)
|
||||||
numbers = {key: _number(data, key) for key in _NUMBER_KEYS}
|
numbers = {key: _number(data, key) for key in _NUMBER_KEYS}
|
||||||
flags = {key: _flag(data, key) for key in _FLAG_KEYS}
|
flags = {key: _flag(data, key) for key in _FLAG_KEYS}
|
||||||
record = ResearchRecord(**numbers, **flags)
|
extended = _optional_number(data, "extended_until")
|
||||||
|
record = ResearchRecord(**numbers, **flags, extended_until=extended)
|
||||||
_check_policy(record)
|
_check_policy(record)
|
||||||
return record
|
return record
|
||||||
|
|
||||||
@ -105,10 +121,10 @@ def _check_policy(record: ResearchRecord) -> None:
|
|||||||
msg = "lock ends before it starts"
|
msg = "lock ends before it starts"
|
||||||
elif not record.opened_at < record.until:
|
elif not record.opened_at < record.until:
|
||||||
msg = "window ends before it opens"
|
msg = "window ends before it opens"
|
||||||
elif record.until - record.opened_at > MAX_WINDOW_SECONDS:
|
elif record.ends_at > record.lock_until:
|
||||||
msg = "window is longer than 48 h"
|
|
||||||
elif record.until > record.lock_until:
|
|
||||||
msg = "window outlives its lock"
|
msg = "window outlives its lock"
|
||||||
|
elif record.extended_until is not None and record.extended_until <= record.until:
|
||||||
|
msg = "extension does not extend"
|
||||||
else:
|
else:
|
||||||
return
|
return
|
||||||
raise ResearchStateError(msg)
|
raise ResearchStateError(msg)
|
||||||
|
|||||||
@ -8,10 +8,13 @@ real assignment in ``state.json`` is never read or written, so there is
|
|||||||
nothing to restore afterwards. Everything else the block does to Steam itself
|
nothing to restore afterwards. Everything else the block does to Steam itself
|
||||||
(kill, uninstall, purge) is skipped while the window is open.
|
(kill, uninstall, purge) is skipped while the window is open.
|
||||||
|
|
||||||
Once the deadline passes the record is latched closed (a clock set back cannot
|
Once the deadline (the extension's, if the window was extended) passes, the
|
||||||
reopen it) and every pass is the ordinary :func:`enforce_total_block_tick`
|
record is latched closed (a clock set back cannot reopen it) and every pass is
|
||||||
again: it kills Steam, removes the package, purges its files, rebuilds the
|
the ordinary :func:`enforce_total_block_tick` again: it kills Steam, removes the
|
||||||
firewall chain from the kept IP cache, and puts the full hosts section back.
|
package, rebuilds the firewall chain from the kept IP cache, and puts the full
|
||||||
|
hosts section back. The purge spares ``~/.local/share/Steam`` for the rest of
|
||||||
|
the lock (Librarian's install and saves stay), and since that install could
|
||||||
|
otherwise be launched without the package, every Steam game is killed on sight.
|
||||||
The lock's end date is never involved.
|
The lock's end date is never involved.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@ -86,12 +89,18 @@ def _research_pass(record: ResearchRecord) -> None:
|
|||||||
if not steam_is_installed():
|
if not steam_is_installed():
|
||||||
return
|
return
|
||||||
allowed = {window.LIBRARIAN_APP_ID}
|
allowed = {window.LIBRARIAN_APP_ID}
|
||||||
killed = enforce_allowed_game(allowed, kill_unauthorized=True, strict=True)
|
_kill_games_except(allowed)
|
||||||
for _pid, app_id in killed:
|
|
||||||
send_notification("⛔🎮", f"{app_id} → 🎯 {window.LIBRARIAN_NAME}")
|
|
||||||
guard_installed_games(allowed, strict=True)
|
guard_installed_games(allowed, strict=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _kill_games_except(allowed: set[int]) -> None:
|
||||||
|
"""Kill every running Steam game outside *allowed* (runtimes excepted)."""
|
||||||
|
for _pid, app_id in enforce_allowed_game(
|
||||||
|
allowed, kill_unauthorized=True, strict=True
|
||||||
|
):
|
||||||
|
send_notification("⛔🎮", f"{app_id} → 🎯 {window.LIBRARIAN_NAME}")
|
||||||
|
|
||||||
|
|
||||||
def total_block_pass(config: Config) -> None:
|
def total_block_pass(config: Config) -> None:
|
||||||
"""The total-block branch of one enforce pass.
|
"""The total-block branch of one enforce pass.
|
||||||
|
|
||||||
@ -108,8 +117,14 @@ def total_block_pass(config: Config) -> None:
|
|||||||
except OSError, subprocess.SubprocessError:
|
except OSError, subprocess.SubprocessError:
|
||||||
logger.exception("Research window pass failed; retrying next tick")
|
logger.exception("Research window pass failed; retrying next tick")
|
||||||
return
|
return
|
||||||
if record is not None and not record.closed and at >= record.until:
|
if record is not None and not record.closed and at >= record.ends_at:
|
||||||
record = _latch_closed(record)
|
record = _latch_closed(record)
|
||||||
enforce_total_block_tick()
|
# Used window (or a record that cannot say): the Steam folder is kept, and
|
||||||
|
# so no Steam game may run from it. {0} only makes the allowed set non-empty;
|
||||||
|
# app 0 is the client itself, which the block's own tick kills by name.
|
||||||
|
used = record is not None or window.research_used(at)
|
||||||
|
enforce_total_block_tick(keep_steam_dir=used)
|
||||||
|
if used:
|
||||||
|
_kill_games_except({0})
|
||||||
if record is not None and record.closed and not record.store_reblocked:
|
if record is not None and record.closed and not record.store_reblocked:
|
||||||
_reblock_store(config, record)
|
_reblock_store(config, record)
|
||||||
|
|||||||
@ -4,8 +4,9 @@ kuhy 2026-11-11: to research a game by playing it ("Librarian: Tidy Up the
|
|||||||
Arcane Library", app 4197610) he needs Steam during a total block. This module
|
Arcane Library", app 4197610) he needs Steam during a total block. This module
|
||||||
is the one bounded way to get it, and the rules are all here:
|
is the one bounded way to get it, and the rules are all here:
|
||||||
|
|
||||||
* **At most 48 hours**, as an explicit expiry (``--until``), never an
|
* **Bounded by the lock**: an explicit expiry (``--until``) no later than the
|
||||||
open-ended switch; a rerun never extends it.
|
lock's end, never an open-ended switch. While open, the window may be
|
||||||
|
extended once (to the lock's end at most); nothing shortens it.
|
||||||
* **Once per lock**: the record names the lock it was spent on (that lock's
|
* **Once per lock**: the record names the lock it was spent on (that lock's
|
||||||
``started_at``/``until``) and stays after the window ends.
|
``started_at``/``until``) and stays after the window ends.
|
||||||
* **Fail closed**: a missing, unreadable, unparsable or out-of-policy record
|
* **Fail closed**: a missing, unreadable, unparsable or out-of-policy record
|
||||||
@ -19,6 +20,7 @@ is the one bounded way to get it, and the rules are all here:
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import replace
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
import logging
|
import logging
|
||||||
import time
|
import time
|
||||||
@ -26,7 +28,6 @@ from typing import Final
|
|||||||
|
|
||||||
from steam_backlog_enforcer import _research_record as store
|
from steam_backlog_enforcer import _research_record as store
|
||||||
from steam_backlog_enforcer._research_record import (
|
from steam_backlog_enforcer._research_record import (
|
||||||
MAX_WINDOW_SECONDS,
|
|
||||||
ResearchRecord,
|
ResearchRecord,
|
||||||
ResearchStateError,
|
ResearchStateError,
|
||||||
read_record,
|
read_record,
|
||||||
@ -115,7 +116,11 @@ def parse_until(raw: str) -> datetime:
|
|||||||
|
|
||||||
|
|
||||||
def open_research_window(until: datetime) -> ResearchRecord:
|
def open_research_window(until: datetime) -> ResearchRecord:
|
||||||
"""Record a research window ending at *until* for the lock in force.
|
"""Record a research window ending at *until*, or extend the one in force.
|
||||||
|
|
||||||
|
The first call for a lock opens the window. While that window is open, one
|
||||||
|
later call may extend it, to the lock's end at most. Nothing else reopens,
|
||||||
|
lengthens or shortens it.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
until: The expiry (timezone-aware).
|
until: The expiry (timezone-aware).
|
||||||
@ -125,9 +130,10 @@ def open_research_window(until: datetime) -> ResearchRecord:
|
|||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ResearchRefusedError: With the reason: no active total block, an
|
ResearchRefusedError: With the reason: no active total block, an
|
||||||
unreadable record (fail closed), a window already spent on this
|
unreadable record (fail closed), an expiry that is past (or, for
|
||||||
lock, an expiry that is past, over 48 h away or beyond the lock's
|
an extension, not later than the current one) or beyond the lock's
|
||||||
end, or a record that cannot be written.
|
end, a window already ended or already extended once, or a record
|
||||||
|
that cannot be written.
|
||||||
"""
|
"""
|
||||||
at = now()
|
at = now()
|
||||||
lock = current_lock(at)
|
lock = current_lock(at)
|
||||||
@ -139,15 +145,11 @@ def open_research_window(until: datetime) -> ResearchRecord:
|
|||||||
except ResearchStateError as exc:
|
except ResearchStateError as exc:
|
||||||
msg = f"research record unreadable ({exc}); refusing (fail closed)"
|
msg = f"research record unreadable ({exc}); refusing (fail closed)"
|
||||||
raise ResearchRefusedError(msg) from exc
|
raise ResearchRefusedError(msg) from exc
|
||||||
if previous is not None and _same_lock(previous, lock):
|
|
||||||
ended = datetime.fromtimestamp(previous.until).astimezone()
|
|
||||||
msg = f"a window was already used for this lock (until {ended:%F %H:%M})"
|
|
||||||
raise ResearchRefusedError(msg)
|
|
||||||
deadline = until.timestamp()
|
deadline = until.timestamp()
|
||||||
|
if previous is not None and _same_lock(previous, lock):
|
||||||
|
return _store(_extend(previous, deadline, at, lock[1]))
|
||||||
if deadline <= at:
|
if deadline <= at:
|
||||||
msg = "--until must be in the future"
|
msg = "--until must be in the future"
|
||||||
elif deadline - at > MAX_WINDOW_SECONDS:
|
|
||||||
msg = "--until is more than 48 h from now"
|
|
||||||
elif deadline > lock[1]:
|
elif deadline > lock[1]:
|
||||||
msg = "--until is after the end of the total block"
|
msg = "--until is after the end of the total block"
|
||||||
else:
|
else:
|
||||||
@ -155,6 +157,40 @@ def open_research_window(until: datetime) -> ResearchRecord:
|
|||||||
raise ResearchRefusedError(msg)
|
raise ResearchRefusedError(msg)
|
||||||
|
|
||||||
|
|
||||||
|
def _extend(
|
||||||
|
previous: ResearchRecord, deadline: float, at: float, lock_end: float
|
||||||
|
) -> ResearchRecord:
|
||||||
|
"""*previous* with its single extension, or a refusal saying why not."""
|
||||||
|
if previous.extended_until is not None:
|
||||||
|
msg = "the window was already extended once"
|
||||||
|
elif not previous.is_open(at):
|
||||||
|
msg = "a window was already used for this lock and it has ended"
|
||||||
|
elif deadline <= previous.until:
|
||||||
|
msg = "--until must be later than the window's current end"
|
||||||
|
elif deadline > lock_end:
|
||||||
|
msg = "--until is after the end of the total block"
|
||||||
|
else:
|
||||||
|
return replace(previous, extended_until=deadline)
|
||||||
|
raise ResearchRefusedError(msg)
|
||||||
|
|
||||||
|
|
||||||
|
def research_used(at: float | None = None) -> bool:
|
||||||
|
"""Whether a research window was spent on the lock in force.
|
||||||
|
|
||||||
|
Gates the one irreversible step of the block, the purge of the Steam
|
||||||
|
folder. A record that cannot be read counts as used: when the answer is
|
||||||
|
unknown, nothing is deleted (the block itself stays fully applied).
|
||||||
|
"""
|
||||||
|
lock = current_lock(now() if at is None else at)
|
||||||
|
if lock is None:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
record = read_record()
|
||||||
|
except ResearchStateError:
|
||||||
|
return True
|
||||||
|
return record is not None and _same_lock(record, lock)
|
||||||
|
|
||||||
|
|
||||||
def _store(record: ResearchRecord) -> ResearchRecord:
|
def _store(record: ResearchRecord) -> ResearchRecord:
|
||||||
"""Write *record*, turning a write failure into a refusal."""
|
"""Write *record*, turning a write failure into a refusal."""
|
||||||
try:
|
try:
|
||||||
|
|||||||
@ -7,10 +7,10 @@ mechanisms that enforce it: :mod:`steam_backlog_enforcer._total_block_purge`
|
|||||||
:mod:`steam_backlog_enforcer._total_block_iptables` (Steam unreachable).
|
:mod:`steam_backlog_enforcer._total_block_iptables` (Steam unreachable).
|
||||||
|
|
||||||
No in-app command lifts a block early; the one bounded exception is a single
|
No in-app command lifts a block early; the one bounded exception is a single
|
||||||
<= 48 h Librarian-only window per lock (:mod:`._research_window`) that never
|
Librarian-only window per lock (:mod:`._research_window`, extendable once, to
|
||||||
touches the lock or its end date. Tamper-resistance is guard-lib's: the lock
|
the lock's end) that never touches the lock or its end date. Tamper-resistance
|
||||||
file's ``until`` sits in a chattr-immutable file-guard, and pacman refuses to
|
is guard-lib's: the lock file's ``until`` sits in a chattr-immutable file-guard,
|
||||||
install ``steam`` while the lock is active (package-block).
|
and pacman refuses to install ``steam`` while the lock is active (package-block).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@ -201,11 +201,12 @@ def start_total_block(days: int) -> bool:
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def enforce_total_block_tick() -> None:
|
def enforce_total_block_tick(*, keep_steam_dir: bool = False) -> None:
|
||||||
"""Re-assert the total block.
|
"""Re-assert the total block (every pass while it is active).
|
||||||
|
|
||||||
Called every enforce-loop iteration while :func:`is_total_block_active`
|
Args:
|
||||||
is True.
|
keep_steam_dir: Spare ``~/.local/share/Steam`` in the purge: a research
|
||||||
|
window was used in this lock, so Librarian's install and saves stay.
|
||||||
"""
|
"""
|
||||||
kill_steam_and_launchers(LAUNCHER_PROCESS_NAMES)
|
kill_steam_and_launchers(LAUNCHER_PROCESS_NAMES)
|
||||||
kill_processes_by_name(kill_target_names(config.CONFIG_FILE))
|
kill_processes_by_name(kill_target_names(config.CONFIG_FILE))
|
||||||
@ -214,7 +215,7 @@ def enforce_total_block_tick() -> None:
|
|||||||
logger.warning("Steam reappeared during total block - removing again")
|
logger.warning("Steam reappeared during total block - removing again")
|
||||||
uninstall_steam_package()
|
uninstall_steam_package()
|
||||||
|
|
||||||
purge_steam_and_proton()
|
purge_steam_and_proton(keep_steam_dir=keep_steam_dir)
|
||||||
|
|
||||||
apply_total_block_iptables()
|
apply_total_block_iptables()
|
||||||
refresh_total_block_hosts() # not apply: that keeps a window's open section
|
refresh_total_block_hosts() # not apply: that keeps a window's open section
|
||||||
|
|||||||
@ -41,10 +41,12 @@ _STEAM_PURGE_LOG_FILE = CONFIG_DIR / "total_block_purge_log.json"
|
|||||||
# machine: ~/.steam (symlink farm), ~/steam (secondary/portable install),
|
# machine: ~/.steam (symlink farm), ~/steam (secondary/portable install),
|
||||||
# ~/.local/share/Steam (the real install - steamapps, userdata, screenshots,
|
# ~/.local/share/Steam (the real install - steamapps, userdata, screenshots,
|
||||||
# and compatibilitytools.d's GE-Proton builds all live under here).
|
# and compatibilitytools.d's GE-Proton builds all live under here).
|
||||||
|
STEAM_DATA_DIR = Path.home() / ".local" / "share" / "Steam"
|
||||||
|
|
||||||
_STEAM_REMNANT_PATHS: tuple[Path, ...] = (
|
_STEAM_REMNANT_PATHS: tuple[Path, ...] = (
|
||||||
Path.home() / ".steam",
|
Path.home() / ".steam",
|
||||||
Path.home() / "steam",
|
Path.home() / "steam",
|
||||||
Path.home() / ".local" / "share" / "Steam",
|
STEAM_DATA_DIR,
|
||||||
Path.home() / ".steampath",
|
Path.home() / ".steampath",
|
||||||
Path.home() / ".steampid",
|
Path.home() / ".steampid",
|
||||||
Path.home() / ".config" / "steamtinkerlaunch",
|
Path.home() / ".config" / "steamtinkerlaunch",
|
||||||
@ -153,15 +155,21 @@ def _uninstall_proton_helpers() -> list[str]:
|
|||||||
return removed
|
return removed
|
||||||
|
|
||||||
|
|
||||||
def _remove_steam_remnants() -> list[str]:
|
def _remove_steam_remnants(*, keep_steam_dir: bool = False) -> list[str]:
|
||||||
"""Delete the curated Steam/Proton filesystem remnants that exist.
|
"""Delete the curated Steam/Proton filesystem remnants that exist.
|
||||||
|
|
||||||
|
With *keep_steam_dir* the Steam data folder itself is spared (a research
|
||||||
|
window was used: its install and local saves stay); every other remnant,
|
||||||
|
the secondary ``~/steam`` included, is still removed.
|
||||||
|
|
||||||
Symlinks are unlinked directly rather than following them into
|
Symlinks are unlinked directly rather than following them into
|
||||||
:func:`shutil.rmtree`, since e.g. ``~/.steampath`` -> a file inside
|
:func:`shutil.rmtree`, since e.g. ``~/.steampath`` -> a file inside
|
||||||
``~/.steam``, which this same pass may already have removed.
|
``~/.steam``, which this same pass may already have removed.
|
||||||
"""
|
"""
|
||||||
removed: list[str] = []
|
removed: list[str] = []
|
||||||
for path in _STEAM_REMNANT_PATHS:
|
for path in _STEAM_REMNANT_PATHS:
|
||||||
|
if keep_steam_dir and path == STEAM_DATA_DIR:
|
||||||
|
continue
|
||||||
if not (path.is_symlink() or path.exists()):
|
if not (path.is_symlink() or path.exists()):
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
@ -201,14 +209,18 @@ def _log_steam_purge(removed_paths: list[str], removed_packages: list[str]) -> N
|
|||||||
_atomic_write(_STEAM_PURGE_LOG_FILE, json.dumps(existing, indent=2) + "\n")
|
_atomic_write(_STEAM_PURGE_LOG_FILE, json.dumps(existing, indent=2) + "\n")
|
||||||
|
|
||||||
|
|
||||||
def purge_steam_and_proton() -> None:
|
def purge_steam_and_proton(*, keep_steam_dir: bool = False) -> None:
|
||||||
"""Remove curated Steam/Proton filesystem remnants and helper packages.
|
"""Remove curated Steam/Proton filesystem remnants and helper packages.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
keep_steam_dir: Spare ``~/.local/share/Steam`` (see
|
||||||
|
:func:`_remove_steam_remnants`).
|
||||||
|
|
||||||
Best-effort and re-run every enforce tick, same as the Steam-package
|
Best-effort and re-run every enforce tick, same as the Steam-package
|
||||||
reappearance check: a stat() per fixed path and a ``pacman -Qi`` per
|
reappearance check: a stat() per fixed path and a ``pacman -Qi`` per
|
||||||
helper package are cheap even when there is nothing left to do.
|
helper package are cheap even when there is nothing left to do.
|
||||||
"""
|
"""
|
||||||
removed_paths = _remove_steam_remnants()
|
removed_paths = _remove_steam_remnants(keep_steam_dir=keep_steam_dir)
|
||||||
removed_packages = _uninstall_proton_helpers()
|
removed_packages = _uninstall_proton_helpers()
|
||||||
if removed_paths or removed_packages:
|
if removed_paths or removed_packages:
|
||||||
logger.info(
|
logger.info(
|
||||||
|
|||||||
@ -31,6 +31,7 @@ class Paths:
|
|||||||
hosts_file: Path
|
hosts_file: Path
|
||||||
purge_log_file: Path
|
purge_log_file: Path
|
||||||
remnant_paths: tuple[Path, ...]
|
remnant_paths: tuple[Path, ...]
|
||||||
|
steam_dir: Path
|
||||||
|
|
||||||
|
|
||||||
def build_paths(tmp_path: Path) -> Paths:
|
def build_paths(tmp_path: Path) -> Paths:
|
||||||
@ -57,6 +58,7 @@ def build_paths(tmp_path: Path) -> Paths:
|
|||||||
hosts_file=tmp_path / "hosts",
|
hosts_file=tmp_path / "hosts",
|
||||||
purge_log_file=tmp_path / "total_block_purge_log.json",
|
purge_log_file=tmp_path / "total_block_purge_log.json",
|
||||||
remnant_paths=remnant_paths,
|
remnant_paths=remnant_paths,
|
||||||
|
steam_dir=remnant_paths[2],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -241,5 +241,6 @@ def total_block_paths(tmp_path: Path) -> Iterator[Paths]:
|
|||||||
patch(f"{HOSTS}.HOSTS_FILE", built.hosts_file),
|
patch(f"{HOSTS}.HOSTS_FILE", built.hosts_file),
|
||||||
patch(f"{PURGE}._STEAM_PURGE_LOG_FILE", built.purge_log_file),
|
patch(f"{PURGE}._STEAM_PURGE_LOG_FILE", built.purge_log_file),
|
||||||
patch(f"{PURGE}._STEAM_REMNANT_PATHS", built.remnant_paths),
|
patch(f"{PURGE}._STEAM_REMNANT_PATHS", built.remnant_paths),
|
||||||
|
patch(f"{PURGE}.STEAM_DATA_DIR", built.steam_dir),
|
||||||
):
|
):
|
||||||
yield built
|
yield built
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
"""The `total-block-research` command: root-only, bounded, lock-exempt."""
|
"""The `total-block-research` command: root-only, to the lock end, lock-exempt."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@ -19,7 +19,7 @@ from steam_backlog_enforcer._command_locks import (
|
|||||||
)
|
)
|
||||||
from steam_backlog_enforcer.config import Config, State
|
from steam_backlog_enforcer.config import Config, State
|
||||||
from steam_backlog_enforcer.main import _dispatch_extra_command
|
from steam_backlog_enforcer.main import _dispatch_extra_command
|
||||||
from steam_backlog_enforcer.tests._research_helpers import HOUR, NOW, lock
|
from steam_backlog_enforcer.tests._research_helpers import HOUR, LOCK_END, NOW, lock
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from collections.abc import Iterator
|
from collections.abc import Iterator
|
||||||
@ -72,19 +72,41 @@ class TestCommand:
|
|||||||
assert cmd.cmd_total_block_research(["--until", UNTIL]) == 1
|
assert cmd.cmd_total_block_research(["--until", UNTIL]) == 1
|
||||||
assert window.read_record() is None
|
assert window.read_record() is None
|
||||||
|
|
||||||
def test_over_48_hours_is_refused(self, capsys: pytest.CaptureFixture[str]) -> None:
|
def test_after_the_lock_end_is_refused(
|
||||||
"""Test that the cap is enforced by the command."""
|
self, capsys: pytest.CaptureFixture[str]
|
||||||
late = datetime.fromtimestamp(NOW + 49 * HOUR, tz=UTC).isoformat()
|
) -> None:
|
||||||
|
"""Test that the lock's end is the ceiling, with the reason printed."""
|
||||||
|
late = datetime.fromtimestamp(LOCK_END + 1, tz=UTC).isoformat()
|
||||||
assert cmd.cmd_total_block_research(["--until", late]) == 1
|
assert cmd.cmd_total_block_research(["--until", late]) == 1
|
||||||
assert "48" in capsys.readouterr().out
|
assert "end of the total block" in capsys.readouterr().out
|
||||||
assert window.read_record() is None
|
assert window.read_record() is None
|
||||||
|
|
||||||
def test_second_run_is_refused(self) -> None:
|
def test_second_run_extends_once(self, capsys: pytest.CaptureFixture[str]) -> None:
|
||||||
"""Test that the second run is refused and the first expiry stands."""
|
"""Test that a later expiry extends the open window, one time only."""
|
||||||
assert cmd.cmd_total_block_research(["--until", UNTIL]) == 0
|
assert cmd.cmd_total_block_research(["--until", UNTIL]) == 0
|
||||||
first = window.read_record()
|
first = window.read_record()
|
||||||
|
assert first is not None
|
||||||
|
assert "extendable once" in capsys.readouterr().out
|
||||||
later = datetime.fromtimestamp(NOW + 30 * HOUR, tz=UTC).isoformat()
|
later = datetime.fromtimestamp(NOW + 30 * HOUR, tz=UTC).isoformat()
|
||||||
assert cmd.cmd_total_block_research(["--until", later]) == 1
|
assert cmd.cmd_total_block_research(["--until", later]) == 0
|
||||||
|
out = capsys.readouterr().out
|
||||||
|
assert "extended until" in out
|
||||||
|
assert "extendable once" not in out
|
||||||
|
assert "the one extension" in out
|
||||||
|
record = window.read_record()
|
||||||
|
assert record is not None
|
||||||
|
assert (record.opened_at, record.until) == (first.opened_at, first.until)
|
||||||
|
assert record.extended_until == NOW + 30 * HOUR
|
||||||
|
again = datetime.fromtimestamp(NOW + 31 * HOUR, tz=UTC).isoformat()
|
||||||
|
assert cmd.cmd_total_block_research(["--until", again]) == 1
|
||||||
|
assert window.read_record() == record
|
||||||
|
|
||||||
|
def test_earlier_expiry_never_shortens(self) -> None:
|
||||||
|
"""Test that a rerun with an earlier time leaves the window alone."""
|
||||||
|
assert cmd.cmd_total_block_research(["--until", UNTIL]) == 0
|
||||||
|
first = window.read_record()
|
||||||
|
sooner = datetime.fromtimestamp(NOW + HOUR, tz=UTC).isoformat()
|
||||||
|
assert cmd.cmd_total_block_research(["--until", sooner]) == 1
|
||||||
assert window.read_record() == first
|
assert window.read_record() == first
|
||||||
|
|
||||||
def test_no_active_block_is_refused(self, total_block_paths: Paths) -> None:
|
def test_no_active_block_is_refused(self, total_block_paths: Paths) -> None:
|
||||||
|
|||||||
@ -238,7 +238,7 @@ class TestEnforceTotalBlockLock:
|
|||||||
assert (
|
assert (
|
||||||
frozenset({"status", "enforce", "gaming-status", "gaming-unblock", "serve"})
|
frozenset({"status", "enforce", "gaming-status", "gaming-unblock", "serve"})
|
||||||
| {"total-block-refresh"} # reconciles the list; cannot shorten the lock
|
| {"total-block-refresh"} # reconciles the list; cannot shorten the lock
|
||||||
| {"total-block-research"} # <= 48 h, once per lock, Librarian only
|
| {"total-block-research"} # once per lock, Librarian only
|
||||||
== _TOTAL_BLOCK_EXEMPT_COMMANDS
|
== _TOTAL_BLOCK_EXEMPT_COMMANDS
|
||||||
)
|
)
|
||||||
assert "gaming-reset" not in _TOTAL_BLOCK_EXEMPT_COMMANDS
|
assert "gaming-reset" not in _TOTAL_BLOCK_EXEMPT_COMMANDS
|
||||||
|
|||||||
@ -20,7 +20,7 @@ class TestExpiry:
|
|||||||
record = window.read_record()
|
record = window.read_record()
|
||||||
assert record is not None
|
assert record is not None
|
||||||
assert record.closed is True
|
assert record.closed is True
|
||||||
tm.block_tick.assert_called_once_with()
|
tm.block_tick.assert_called_once_with(keep_steam_dir=True)
|
||||||
tm.reconcile.assert_not_called()
|
tm.reconcile.assert_not_called()
|
||||||
|
|
||||||
def test_store_is_reblocked_once(self, tm: Mocks) -> None:
|
def test_store_is_reblocked_once(self, tm: Mocks) -> None:
|
||||||
@ -79,5 +79,44 @@ class TestExpiry:
|
|||||||
window.write_record(make_record())
|
window.write_record(make_record())
|
||||||
with patch.object(window, "write_record", side_effect=OSError("ro")):
|
with patch.object(window, "write_record", side_effect=OSError("ro")):
|
||||||
run_pass(NOW + 2 * HOUR)
|
run_pass(NOW + 2 * HOUR)
|
||||||
tm.block_tick.assert_called_once_with()
|
tm.block_tick.assert_called_once_with(keep_steam_dir=True)
|
||||||
tm.reconcile.assert_not_called()
|
tm.reconcile.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
class TestAfterTheWindow:
|
||||||
|
"""The block returns without the purge, and no Steam game may run."""
|
||||||
|
|
||||||
|
def test_steam_folder_is_kept_for_the_rest_of_the_lock(self, tm: Mocks) -> None:
|
||||||
|
"""Test that every later tick also keeps the folder."""
|
||||||
|
window.write_record(make_record())
|
||||||
|
for later in (2 * HOUR, 3 * HOUR, 30 * HOUR):
|
||||||
|
run_pass(NOW + later)
|
||||||
|
assert [c.kwargs for c in tm.block_tick.call_args_list] == [
|
||||||
|
{"keep_steam_dir": True}
|
||||||
|
] * 3
|
||||||
|
|
||||||
|
def test_extended_window_expires_at_the_extension(self, tm: Mocks) -> None:
|
||||||
|
"""Test that the latch waits for the extended deadline."""
|
||||||
|
window.write_record(make_record(extended_until=NOW + 9 * HOUR))
|
||||||
|
run_pass(NOW + 4 * HOUR)
|
||||||
|
record = window.read_record()
|
||||||
|
assert record is not None
|
||||||
|
assert record.closed is False
|
||||||
|
run_pass(NOW + 9 * HOUR)
|
||||||
|
record = window.read_record()
|
||||||
|
assert record is not None
|
||||||
|
assert record.closed is True
|
||||||
|
tm.block_tick.assert_called_once_with(keep_steam_dir=True)
|
||||||
|
|
||||||
|
def test_any_steam_game_is_killed_once_the_window_is_over(self, tm: Mocks) -> None:
|
||||||
|
"""Test that the kept install cannot be played outside the window."""
|
||||||
|
tm.enforce.return_value = [(4242, window.LIBRARIAN_APP_ID)]
|
||||||
|
window.write_record(make_record(closed=True, store_reblocked=True))
|
||||||
|
run_pass(NOW + 5 * HOUR)
|
||||||
|
tm.enforce.assert_called_once_with({0}, kill_unauthorized=True, strict=True)
|
||||||
|
tm.notify.assert_called_once()
|
||||||
|
|
||||||
|
def test_no_game_scan_when_no_window_was_ever_used(self, tm: Mocks) -> None:
|
||||||
|
"""Test that an untouched total block keeps its old behaviour."""
|
||||||
|
run_pass()
|
||||||
|
tm.enforce.assert_not_called()
|
||||||
|
|||||||
@ -1,7 +1,8 @@
|
|||||||
"""Opening a research window: the 48 h cap, once per lock, fail closed."""
|
"""Opening a research window: up to the lock end, one extension, fail closed."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import replace
|
||||||
from datetime import UTC, datetime
|
from datetime import UTC, datetime
|
||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
@ -58,14 +59,16 @@ class TestOpen:
|
|||||||
assert (record.opened_at, record.until) == (NOW, NOW + 10 * HOUR)
|
assert (record.opened_at, record.until) == (NOW, NOW + 10 * HOUR)
|
||||||
assert (record.closed, record.store_reblocked) == (False, False)
|
assert (record.closed, record.store_reblocked) == (False, False)
|
||||||
|
|
||||||
def test_exactly_48_hours_is_allowed(self) -> None:
|
def test_up_to_the_lock_end_is_allowed(self) -> None:
|
||||||
"""Test that the cap is inclusive."""
|
"""Test that the only cap is the end of the lock (no 48 h limit)."""
|
||||||
assert _open(48 * HOUR).until == NOW + 48 * HOUR
|
record = _open(LOCK_END - NOW)
|
||||||
|
assert record.until == LOCK_END
|
||||||
|
assert record.until - record.opened_at > 48 * HOUR
|
||||||
|
|
||||||
def test_more_than_48_hours_is_refused(self) -> None:
|
def test_one_second_past_the_lock_end_is_refused(self) -> None:
|
||||||
"""Test that one second over the cap is refused and nothing written."""
|
"""Test that the lock's end is a hard ceiling and nothing is written."""
|
||||||
with pytest.raises(window.ResearchRefusedError, match="48"):
|
with pytest.raises(window.ResearchRefusedError, match="end of the total"):
|
||||||
_open(48 * HOUR + 1)
|
_open(LOCK_END - NOW + 1)
|
||||||
assert window.read_record() is None
|
assert window.read_record() is None
|
||||||
|
|
||||||
@pytest.mark.parametrize("offset", [0.0, -1.0, -3 * HOUR])
|
@pytest.mark.parametrize("offset", [0.0, -1.0, -3 * HOUR])
|
||||||
@ -113,15 +116,64 @@ class TestNoLock:
|
|||||||
|
|
||||||
@pytest.mark.usefixtures("live")
|
@pytest.mark.usefixtures("live")
|
||||||
class TestOncePerLock:
|
class TestOncePerLock:
|
||||||
"""One window per lock, however it ended; reruns never extend."""
|
"""One window per lock; the open one may be extended once, never more."""
|
||||||
|
|
||||||
def test_second_open_is_refused_and_changes_nothing(self) -> None:
|
def test_extension_moves_only_the_deadline(self) -> None:
|
||||||
"""Test that a rerun with a later expiry never extends the window."""
|
"""Test that a later expiry extends an open window, nothing else."""
|
||||||
|
first = _open(2 * HOUR)
|
||||||
|
extended = _open(40 * HOUR)
|
||||||
|
assert extended == replace(first, extended_until=NOW + 40 * HOUR)
|
||||||
|
assert window.read_record() == extended
|
||||||
|
|
||||||
|
def test_extension_up_to_the_lock_end(self) -> None:
|
||||||
|
"""Test that the extension may reach the lock end exactly."""
|
||||||
_open(2 * HOUR)
|
_open(2 * HOUR)
|
||||||
|
assert _open(LOCK_END - NOW).extended_until == LOCK_END
|
||||||
|
|
||||||
|
def test_extension_past_the_lock_end_is_refused(self) -> None:
|
||||||
|
"""Test that no extension goes beyond the lock, even by a second."""
|
||||||
|
first = _open(2 * HOUR)
|
||||||
|
with pytest.raises(window.ResearchRefusedError, match="end of the total"):
|
||||||
|
_open(LOCK_END - NOW + 1)
|
||||||
|
assert window.read_record() == first
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("offset", [2 * HOUR, 2 * HOUR - 1, HOUR, 60.0])
|
||||||
|
def test_same_or_earlier_expiry_is_refused(self, offset: float) -> None:
|
||||||
|
"""Test that an extension can only make the window longer."""
|
||||||
|
first = _open(2 * HOUR)
|
||||||
before = store.RESEARCH_FILE.read_bytes()
|
before = store.RESEARCH_FILE.read_bytes()
|
||||||
with pytest.raises(window.ResearchRefusedError, match="already"):
|
with pytest.raises(window.ResearchRefusedError, match="later"):
|
||||||
_open(40 * HOUR)
|
_open(offset)
|
||||||
assert store.RESEARCH_FILE.read_bytes() == before
|
assert store.RESEARCH_FILE.read_bytes() == before
|
||||||
|
assert window.read_record() == first
|
||||||
|
|
||||||
|
def test_only_one_extension(self) -> None:
|
||||||
|
"""Test that the second extension is refused and changes nothing."""
|
||||||
|
_open(2 * HOUR)
|
||||||
|
_open(40 * HOUR)
|
||||||
|
before = store.RESEARCH_FILE.read_bytes()
|
||||||
|
with pytest.raises(window.ResearchRefusedError, match="once"):
|
||||||
|
_open(60 * HOUR)
|
||||||
|
assert store.RESEARCH_FILE.read_bytes() == before
|
||||||
|
|
||||||
|
def test_an_ended_window_cannot_be_extended(self) -> None:
|
||||||
|
"""Test that extending after the deadline would be a second window."""
|
||||||
|
_open(2 * HOUR)
|
||||||
|
with (
|
||||||
|
patch(NOW_PATCH, return_value=NOW + 3 * HOUR),
|
||||||
|
pytest.raises(window.ResearchRefusedError, match="already"),
|
||||||
|
):
|
||||||
|
window.open_research_window(_at(40 * HOUR))
|
||||||
|
|
||||||
|
def test_extension_write_failure_is_a_refusal(self) -> None:
|
||||||
|
"""Test that a failing write on extension is reported."""
|
||||||
|
first = _open(2 * HOUR)
|
||||||
|
with (
|
||||||
|
patch.object(window, "write_record", side_effect=OSError("ro")),
|
||||||
|
pytest.raises(window.ResearchRefusedError, match="write"),
|
||||||
|
):
|
||||||
|
_open(40 * HOUR)
|
||||||
|
assert window.read_record() == first
|
||||||
|
|
||||||
def test_used_window_stays_used_after_it_closed(self) -> None:
|
def test_used_window_stays_used_after_it_closed(self) -> None:
|
||||||
"""Test that an expired, latched window is not a free second window."""
|
"""Test that an expired, latched window is not a free second window."""
|
||||||
|
|||||||
100
steam_backlog_enforcer/tests/test_research_purge.py
Normal file
100
steam_backlog_enforcer/tests/test_research_purge.py
Normal file
@ -0,0 +1,100 @@
|
|||||||
|
"""The Steam folder survives the purge once a research window was used."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from steam_backlog_enforcer._total_block import enforce_total_block_tick
|
||||||
|
from steam_backlog_enforcer._total_block_purge import (
|
||||||
|
_remove_steam_remnants,
|
||||||
|
purge_steam_and_proton,
|
||||||
|
)
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from steam_backlog_enforcer.tests._total_block_paths import Paths
|
||||||
|
|
||||||
|
PKG = "steam_backlog_enforcer._total_block_purge"
|
||||||
|
BLOCK = "steam_backlog_enforcer._total_block"
|
||||||
|
|
||||||
|
|
||||||
|
def _populate(paths: Paths) -> tuple[Path, Path, Path]:
|
||||||
|
"""Create the Steam folder (with a save), ~/.steam and ~/steam."""
|
||||||
|
save = paths.steam_dir / "steamapps" / "compatdata" / "4197610" / "save.dat"
|
||||||
|
save.parent.mkdir(parents=True)
|
||||||
|
save.write_text("progress", encoding="utf-8")
|
||||||
|
dot_steam, portable = paths.remnant_paths[0], paths.remnant_paths[1]
|
||||||
|
dot_steam.mkdir(parents=True)
|
||||||
|
portable.mkdir(parents=True)
|
||||||
|
return save, dot_steam, portable
|
||||||
|
|
||||||
|
|
||||||
|
class TestKeepSteamDir:
|
||||||
|
"""Only the Steam data folder is spared; every other remnant still goes."""
|
||||||
|
|
||||||
|
def test_default_purges_the_folder_too(self, total_block_paths: Paths) -> None:
|
||||||
|
"""Test that without research nothing changed."""
|
||||||
|
save, dot_steam, portable = _populate(total_block_paths)
|
||||||
|
removed = _remove_steam_remnants()
|
||||||
|
assert str(total_block_paths.steam_dir) in removed
|
||||||
|
assert not save.exists()
|
||||||
|
assert not dot_steam.exists()
|
||||||
|
assert not portable.exists()
|
||||||
|
|
||||||
|
def test_kept_folder_and_its_saves_survive(self, total_block_paths: Paths) -> None:
|
||||||
|
"""Test that the install and local saves are not touched."""
|
||||||
|
save, dot_steam, portable = _populate(total_block_paths)
|
||||||
|
removed = _remove_steam_remnants(keep_steam_dir=True)
|
||||||
|
assert str(total_block_paths.steam_dir) not in removed
|
||||||
|
assert save.read_text(encoding="utf-8") == "progress"
|
||||||
|
assert not dot_steam.exists()
|
||||||
|
assert not portable.exists()
|
||||||
|
|
||||||
|
def test_purge_passes_the_flag_and_logs_only_what_went(
|
||||||
|
self, total_block_paths: Paths
|
||||||
|
) -> None:
|
||||||
|
"""Test that the whole purge honours the flag and logs honestly."""
|
||||||
|
save, _, _ = _populate(total_block_paths)
|
||||||
|
with patch(f"{PKG}.is_package_installed", return_value=False):
|
||||||
|
purge_steam_and_proton(keep_steam_dir=True)
|
||||||
|
assert save.exists()
|
||||||
|
logged = json.loads(total_block_paths.purge_log_file.read_text("utf-8"))
|
||||||
|
assert str(total_block_paths.steam_dir) not in logged[0]["removed_paths"]
|
||||||
|
|
||||||
|
def test_default_purge_still_removes_the_folder(
|
||||||
|
self, total_block_paths: Paths
|
||||||
|
) -> None:
|
||||||
|
"""Test that the old call signature keeps its old behaviour."""
|
||||||
|
save, _, _ = _populate(total_block_paths)
|
||||||
|
with patch(f"{PKG}.is_package_installed", return_value=False):
|
||||||
|
purge_steam_and_proton()
|
||||||
|
assert not save.exists()
|
||||||
|
|
||||||
|
|
||||||
|
class TestTickPassesTheFlag:
|
||||||
|
"""enforce_total_block_tick is the only caller on the hot path."""
|
||||||
|
|
||||||
|
def _tick(self, **kwargs: bool) -> object:
|
||||||
|
with (
|
||||||
|
patch(f"{BLOCK}.kill_steam_and_launchers", return_value=[]),
|
||||||
|
patch(f"{BLOCK}.kill_processes_by_name", return_value=[]),
|
||||||
|
patch(f"{BLOCK}.is_steam_installed", return_value=False),
|
||||||
|
patch(f"{BLOCK}.apply_total_block_iptables", return_value=True),
|
||||||
|
patch(f"{BLOCK}.refresh_total_block_hosts", return_value=True),
|
||||||
|
patch(f"{BLOCK}.purge_steam_and_proton") as purge,
|
||||||
|
):
|
||||||
|
enforce_total_block_tick(**kwargs)
|
||||||
|
return purge
|
||||||
|
|
||||||
|
def test_default_purges_everything(self) -> None:
|
||||||
|
"""Test that the default is the full purge."""
|
||||||
|
purge = self._tick()
|
||||||
|
purge.assert_called_once_with(keep_steam_dir=False)
|
||||||
|
|
||||||
|
def test_keep_flag_reaches_the_purge(self) -> None:
|
||||||
|
"""Test that the research exemption reaches the purge."""
|
||||||
|
purge = self._tick(keep_steam_dir=True)
|
||||||
|
purge.assert_called_once_with(keep_steam_dir=True)
|
||||||
@ -25,6 +25,7 @@ def _raw(**changes: object) -> str:
|
|||||||
"until": NOW + HOUR,
|
"until": NOW + HOUR,
|
||||||
"closed": False,
|
"closed": False,
|
||||||
"store_reblocked": False,
|
"store_reblocked": False,
|
||||||
|
"extended_until": None,
|
||||||
}
|
}
|
||||||
for key, value in changes.items():
|
for key, value in changes.items():
|
||||||
if value is None:
|
if value is None:
|
||||||
@ -66,9 +67,14 @@ class TestParse:
|
|||||||
_raw(lock_until=LOCK_START),
|
_raw(lock_until=LOCK_START),
|
||||||
_raw(until=LOCK_END + 1),
|
_raw(until=LOCK_END + 1),
|
||||||
_raw(opened_at=LOCK_END - HOUR, until=LOCK_END + HOUR),
|
_raw(opened_at=LOCK_END - HOUR, until=LOCK_END + HOUR),
|
||||||
_raw(until=NOW - 60 + 48 * HOUR + 2),
|
|
||||||
_raw(closed="yes"),
|
_raw(closed="yes"),
|
||||||
_raw(store_reblocked=1),
|
_raw(store_reblocked=1),
|
||||||
|
_raw(extended_until="later"),
|
||||||
|
_raw(extended_until=True),
|
||||||
|
_raw(extended_until=float("nan")),
|
||||||
|
_raw(extended_until=NOW + HOUR),
|
||||||
|
_raw(extended_until=NOW),
|
||||||
|
_raw(extended_until=LOCK_END + 1),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
def test_invalid_is_an_error(self, raw: str) -> None:
|
def test_invalid_is_an_error(self, raw: str) -> None:
|
||||||
@ -76,10 +82,19 @@ class TestParse:
|
|||||||
with pytest.raises(store.ResearchStateError):
|
with pytest.raises(store.ResearchStateError):
|
||||||
store.parse_record(raw)
|
store.parse_record(raw)
|
||||||
|
|
||||||
def test_exactly_48_hours_is_valid(self) -> None:
|
def test_no_cap_but_the_lock_end(self) -> None:
|
||||||
"""Test that the cap is inclusive."""
|
"""Test that a window may run to the lock's end, however long."""
|
||||||
parsed = store.parse_record(_raw(until=NOW - 60 + 48 * HOUR))
|
parsed = store.parse_record(_raw(until=LOCK_END))
|
||||||
assert parsed.until - parsed.opened_at == 48 * HOUR
|
assert parsed.until - parsed.opened_at > 48 * HOUR
|
||||||
|
|
||||||
|
def test_extension_roundtrip_and_old_records_have_none(self) -> None:
|
||||||
|
"""Test that extended_until survives and is absent in an old record."""
|
||||||
|
record = make_record(extended_until=LOCK_END)
|
||||||
|
assert store.parse_record(record.to_json()) == record
|
||||||
|
assert store.parse_record(_raw(extended_until=None)).extended_until is None
|
||||||
|
old = json.loads(_raw())
|
||||||
|
del old["extended_until"]
|
||||||
|
assert store.parse_record(json.dumps(old)).extended_until is None
|
||||||
|
|
||||||
|
|
||||||
class TestReadWrite:
|
class TestReadWrite:
|
||||||
@ -134,6 +149,17 @@ class TestIsOpen:
|
|||||||
"""Test that a late clock is closed."""
|
"""Test that a late clock is closed."""
|
||||||
assert not make_record().is_open(NOW + 5 * HOUR)
|
assert not make_record().is_open(NOW + 5 * HOUR)
|
||||||
|
|
||||||
|
def test_extension_moves_the_deadline(self) -> None:
|
||||||
|
"""Test that an extended window is open past its first deadline."""
|
||||||
|
record = make_record(extended_until=NOW + 5 * HOUR)
|
||||||
|
assert record.ends_at == NOW + 5 * HOUR
|
||||||
|
assert record.is_open(NOW + 2 * HOUR)
|
||||||
|
assert not record.is_open(NOW + 5 * HOUR)
|
||||||
|
|
||||||
|
def test_without_extension_ends_at_until(self) -> None:
|
||||||
|
"""Test that ends_at is the plain deadline by default."""
|
||||||
|
assert make_record().ends_at == NOW + HOUR
|
||||||
|
|
||||||
def test_latch_wins_over_the_clock(self) -> None:
|
def test_latch_wins_over_the_clock(self) -> None:
|
||||||
"""Test that a closed record stays closed even for an in-range clock."""
|
"""Test that a closed record stays closed even for an in-range clock."""
|
||||||
assert not make_record(closed=True).is_open(NOW)
|
assert not make_record(closed=True).is_open(NOW)
|
||||||
|
|||||||
@ -19,7 +19,7 @@ class TestFullBlock:
|
|||||||
def test_no_record_runs_the_full_tick(self, tm: Mocks) -> None:
|
def test_no_record_runs_the_full_tick(self, tm: Mocks) -> None:
|
||||||
"""Test that the default is the full block."""
|
"""Test that the default is the full block."""
|
||||||
run_pass()
|
run_pass()
|
||||||
tm.block_tick.assert_called_once_with()
|
tm.block_tick.assert_called_once_with(keep_steam_dir=False)
|
||||||
tm.reconcile.assert_not_called()
|
tm.reconcile.assert_not_called()
|
||||||
tm.enforce.assert_not_called()
|
tm.enforce.assert_not_called()
|
||||||
|
|
||||||
@ -28,14 +28,14 @@ class TestFullBlock:
|
|||||||
store.RESEARCH_FILE.parent.mkdir(parents=True)
|
store.RESEARCH_FILE.parent.mkdir(parents=True)
|
||||||
store.RESEARCH_FILE.write_text("{oops", encoding="utf-8")
|
store.RESEARCH_FILE.write_text("{oops", encoding="utf-8")
|
||||||
run_pass()
|
run_pass()
|
||||||
tm.block_tick.assert_called_once_with()
|
tm.block_tick.assert_called_once_with(keep_steam_dir=True)
|
||||||
tm.reconcile.assert_not_called()
|
tm.reconcile.assert_not_called()
|
||||||
|
|
||||||
def test_clock_before_opening_blocks_without_latching(self, tm: Mocks) -> None:
|
def test_clock_before_opening_blocks_without_latching(self, tm: Mocks) -> None:
|
||||||
"""Test that a clock set back blocks, but does not burn the window."""
|
"""Test that a clock set back blocks, but does not burn the window."""
|
||||||
window.write_record(make_record())
|
window.write_record(make_record())
|
||||||
run_pass(NOW - 3 * HOUR)
|
run_pass(NOW - 3 * HOUR)
|
||||||
tm.block_tick.assert_called_once_with()
|
tm.block_tick.assert_called_once_with(keep_steam_dir=True)
|
||||||
tm.reconcile.assert_not_called()
|
tm.reconcile.assert_not_called()
|
||||||
record = window.read_record()
|
record = window.read_record()
|
||||||
assert record is not None
|
assert record is not None
|
||||||
@ -45,13 +45,22 @@ class TestFullBlock:
|
|||||||
"""Test that a finished window costs nothing but the block tick."""
|
"""Test that a finished window costs nothing but the block tick."""
|
||||||
window.write_record(make_record(closed=True, store_reblocked=True))
|
window.write_record(make_record(closed=True, store_reblocked=True))
|
||||||
run_pass(NOW + 5 * HOUR)
|
run_pass(NOW + 5 * HOUR)
|
||||||
tm.block_tick.assert_called_once_with()
|
tm.block_tick.assert_called_once_with(keep_steam_dir=True)
|
||||||
tm.restore_store.assert_not_called()
|
tm.restore_store.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
class TestOpenWindow:
|
class TestOpenWindow:
|
||||||
"""Inside the window: Steam is left alone, everything but Librarian is not."""
|
"""Inside the window: Steam is left alone, everything but Librarian is not."""
|
||||||
|
|
||||||
|
def test_extended_window_stays_open_past_its_first_deadline(
|
||||||
|
self, tm: Mocks
|
||||||
|
) -> None:
|
||||||
|
"""Test that the extension keeps the research pass running."""
|
||||||
|
window.write_record(make_record(extended_until=NOW + 9 * HOUR))
|
||||||
|
run_pass(NOW + 4 * HOUR)
|
||||||
|
tm.reconcile.assert_called_once()
|
||||||
|
tm.block_tick.assert_not_called()
|
||||||
|
|
||||||
def test_reconciles_and_skips_the_full_block(self, tm: Mocks) -> None:
|
def test_reconciles_and_skips_the_full_block(self, tm: Mocks) -> None:
|
||||||
"""Test that the open window replaces the block tick."""
|
"""Test that the open window replaces the block tick."""
|
||||||
window.write_record(make_record())
|
window.write_record(make_record())
|
||||||
|
|||||||
@ -7,6 +7,8 @@ import logging
|
|||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
from steam_backlog_enforcer import _research_record as store
|
from steam_backlog_enforcer import _research_record as store
|
||||||
from steam_backlog_enforcer import _research_window as window
|
from steam_backlog_enforcer import _research_window as window
|
||||||
from steam_backlog_enforcer.tests._research_helpers import (
|
from steam_backlog_enforcer.tests._research_helpers import (
|
||||||
@ -19,8 +21,6 @@ from steam_backlog_enforcer.tests._research_helpers import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
import pytest
|
|
||||||
|
|
||||||
from steam_backlog_enforcer.tests._total_block_paths import Paths
|
from steam_backlog_enforcer.tests._total_block_paths import Paths
|
||||||
|
|
||||||
NOW_PATCH = "steam_backlog_enforcer._research_window.now"
|
NOW_PATCH = "steam_backlog_enforcer._research_window.now"
|
||||||
@ -143,3 +143,46 @@ class TestOpenNow:
|
|||||||
with patch("steam_backlog_enforcer._research_window.time.time") as clock:
|
with patch("steam_backlog_enforcer._research_window.time.time") as clock:
|
||||||
clock.return_value = 42.5
|
clock.return_value = 42.5
|
||||||
assert window.now() == 42.5
|
assert window.now() == 42.5
|
||||||
|
|
||||||
|
|
||||||
|
class TestResearchUsed:
|
||||||
|
"""research_used decides whether the Steam folder may be purged."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _used() -> bool:
|
||||||
|
with patch(NOW_PATCH, return_value=NOW):
|
||||||
|
return window.research_used()
|
||||||
|
|
||||||
|
def test_never_used(self, total_block_paths: Paths) -> None:
|
||||||
|
"""Test that a lock without a record purges as before."""
|
||||||
|
lock(total_block_paths)
|
||||||
|
assert self._used() is False
|
||||||
|
|
||||||
|
def test_no_lock(self) -> None:
|
||||||
|
"""Test that without a total block nothing is kept on its account."""
|
||||||
|
window.write_record(make_record())
|
||||||
|
assert self._used() is False
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("closed", [False, True])
|
||||||
|
def test_used_for_this_lock(
|
||||||
|
self, total_block_paths: Paths, *, closed: bool
|
||||||
|
) -> None:
|
||||||
|
"""Test that an open or ended window both protect the Steam folder."""
|
||||||
|
lock(total_block_paths)
|
||||||
|
window.write_record(make_record(closed=closed))
|
||||||
|
assert self._used() is True
|
||||||
|
|
||||||
|
def test_other_locks_record_does_not_protect(
|
||||||
|
self, total_block_paths: Paths
|
||||||
|
) -> None:
|
||||||
|
"""Test that last lock's window gives this lock no exemption."""
|
||||||
|
lock(total_block_paths)
|
||||||
|
window.write_record(make_record(lock_started_at=LOCK_START - 99.0))
|
||||||
|
assert self._used() is False
|
||||||
|
|
||||||
|
def test_unreadable_record_keeps_the_data(self, total_block_paths: Paths) -> None:
|
||||||
|
"""Test that when the record cannot say, nothing irreversible happens."""
|
||||||
|
lock(total_block_paths)
|
||||||
|
store.RESEARCH_FILE.parent.mkdir(parents=True)
|
||||||
|
store.RESEARCH_FILE.write_text("{oops", encoding="utf-8")
|
||||||
|
assert self._used() is True
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user