mirror of
https://github.com/kuhyx/testsAndMisc.git
synced 2026-11-24 19:16:18 +01:00
Compare commits
3 Commits
f58caea2ab
...
197cf67b7f
| Author | SHA1 | Date | |
|---|---|---|---|
| 197cf67b7f | |||
| 16c626661d | |||
| 324ec0c9b5 |
@ -0,0 +1,17 @@
|
||||
{
|
||||
"title": "Split wsg_grabber/downloader.py under the 250-line cap",
|
||||
"objective": "Bring python_pkg/wsg_grabber/downloader.py (420 lines) under the repo-wide 250-line file cap by separating the Worker class's two independent halves -- walking the board and fetching a claimed file -- into mixins, with no change to behaviour, to the public Worker API, or to how the tests drive it.",
|
||||
"acceptance_criteria": [
|
||||
"downloader.py, _scan.py, _fetch.py and _worker_base.py are each at most 250 lines.",
|
||||
"All 277 python_pkg/wsg_grabber tests pass unchanged, including the ones that call worker._download_one() and worker._fetch_thread() as bound methods.",
|
||||
"The package holds 100% branch coverage: no new uncovered lines are introduced by the split (in particular, no NotImplementedError stub bodies).",
|
||||
"pre-commit passes on all four files with no suppression added -- no # noqa, no # type: ignore, no pylint disable, no new per-file-ignores in meta/pyproject.toml."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Any behaviour, retry, backoff or state-transition change.",
|
||||
"Any change to the test files.",
|
||||
"Splitting the wsg_grabber test files -- that is separate work.",
|
||||
"Adding pylint mixin configuration to meta/pyproject.toml."
|
||||
],
|
||||
"verifier": "pre-commit run --files python_pkg/wsg_grabber/downloader.py python_pkg/wsg_grabber/_scan.py python_pkg/wsg_grabber/_fetch.py python_pkg/wsg_grabber/_worker_base.py (runs ruff, ruff format, mypy, pylint, bandit and the coverage-gated pytest), plus bash ~/utils/scripts/check_file_length.sh --all for the cap itself."
|
||||
}
|
||||
@ -0,0 +1,43 @@
|
||||
{
|
||||
"intent": "Bring python_pkg/wsg_grabber/downloader.py under the 250-line file cap by splitting the Worker class's board-walking and file-fetching halves into mixins, keeping every method reachable as a bound attribute of Worker.",
|
||||
"scope": [
|
||||
"python_pkg/wsg_grabber/downloader.py",
|
||||
"python_pkg/wsg_grabber/_scan.py (new)",
|
||||
"python_pkg/wsg_grabber/_fetch.py (new)",
|
||||
"python_pkg/wsg_grabber/_worker_base.py (new)",
|
||||
"Non-goal: no behaviour change, no test changes, no pylint config change"
|
||||
],
|
||||
"changes": [
|
||||
"Moved the board-walking methods -- _scan_step, _refresh_thread_list, _archive_refs, _conditional_get, _fetch_thread, _write_off_deleted -- into ScanMixin in _scan.py.",
|
||||
"Moved _download_one and _apply_result into DownloadMixin in _fetch.py.",
|
||||
"Added _worker_base.py holding WorkerBase(ABC): the state both halves touch, plus abstract _get_json / _publish / _wait_for_slot which Worker supplies. Both mixins inherit from it, so neither redeclares the other's bookkeeping.",
|
||||
"Worker is now `class Worker(ScanMixin, DownloadMixin)`; __init__ is unchanged and remains the only place instance state is created.",
|
||||
"downloader.py 420 -> 238 lines; _scan.py 134; _fetch.py 98; _worker_base.py 52."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "python3 -m pytest python_pkg/wsg_grabber/tests/ -q",
|
||||
"result": "pass",
|
||||
"evidence": "277 passed in 15.20s, unchanged from before the split. This is the load-bearing check: test_downloader_part2.py calls worker._download_one() and worker._fetch_thread(ThreadRef(7, 100)) as bound methods and sets worker._catalog_fresh directly, so the mixin composition is exercised rather than assumed."
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run --files python_pkg/wsg_grabber/downloader.py python_pkg/wsg_grabber/_scan.py python_pkg/wsg_grabber/_fetch.py python_pkg/wsg_grabber/_worker_base.py",
|
||||
"result": "pass",
|
||||
"evidence": "ruff, ruff format, mypy, pylint, bandit and the coverage-gated pytest all pass. The only remaining hook failures were 'no staged evidence artifact' and 'no workflow contract', which this file and the paired contract satisfy. No suppression was added."
|
||||
},
|
||||
{
|
||||
"command": "bash ~/utils/scripts/check_file_length.sh --all | grep -c 'over by'",
|
||||
"result": "pass",
|
||||
"evidence": "All four files are under the cap: 238 / 134 / 98 / 52."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"Two intermediate designs failed the gate and were abandoned rather than suppressed. Bare `raise NotImplementedError` stubs on the mixins would have been uncovered lines under the 100% gate; `if TYPE_CHECKING` method stubs satisfied mypy but left pylint reporting no-member. The ABC with real abstract methods satisfies both.",
|
||||
"_downloaded carries a class-level default of 0 rather than a bare annotation, because _fetch does `self._downloaded += 1` and pylint only accepts an attribute as assignable when there is something to assign to. Worker.__init__ still sets the instance value, so no state is shared between instances -- ints are immutable, so the class attribute is never mutated in place.",
|
||||
"Mixin method resolution order now matters: Worker(ScanMixin, DownloadMixin) means ScanMixin wins on any name collision. There are none today; adding a same-named method to both would silently pick ScanMixin's."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; downloader.py returns to its 420-line form and the three new modules are deleted.",
|
||||
"After rollback, run python3 -m pytest python_pkg/wsg_grabber/tests/ -q to confirm 277 tests still pass."
|
||||
]
|
||||
}
|
||||
@ -0,0 +1,37 @@
|
||||
{
|
||||
"intent": "Bring python_pkg/wsg_grabber/player.py under the 250-line file cap by separating the stateless mpv wire protocol and the Player interface from the class that owns the process and socket.",
|
||||
"scope": [
|
||||
"python_pkg/wsg_grabber/player.py",
|
||||
"python_pkg/wsg_grabber/_mpv_ipc.py (new)",
|
||||
"python_pkg/wsg_grabber/_player_api.py (new)",
|
||||
"Non-goal: no behaviour change, no test changes, no change to the mpv command line"
|
||||
],
|
||||
"changes": [
|
||||
"Moved the stateless wire protocol into _mpv_ipc.py: read_reply (was _read_reply), build_argv, encode, note_errors, plus probe_properties and query lifted out of MpvPlayer.probe/_query, which only ever needed the socket path.",
|
||||
"Moved the Player Protocol into _player_api.py; ui.py depends on the interface, not on MpvPlayer.",
|
||||
"Moved the probe constants _PROBE_ID, _PROBE_TIMEOUT_S and _PROBE_PROPERTIES verbatim alongside the code that reads them.",
|
||||
"player.py re-exports Player, build_argv and encode through __all__.",
|
||||
"MpvPlayer._note_errors is kept as a thin bound delegate to _mpv_ipc.note_errors, because test_player.py calls it on the instance and the tests are out of scope for this refactor.",
|
||||
"player.py 373 -> 235 lines; _mpv_ipc.py 158; _player_api.py 49."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "python3 -m pytest python_pkg/wsg_grabber/tests/ -q --cov=python_pkg.wsg_grabber --cov-report=term-missing",
|
||||
"result": "pass",
|
||||
"evidence": "277 passed in 15.14s. _mpv_ipc.py 51 stmts / 14 branches 100%, _player_api.py 100%, player.py 89 stmts 100%. An intermediate version of this split failed with 1 failed / 276 passed because test_mpv_errors_are_logged_rather_than_discarded calls mpv._note_errors as a bound method; the delegate was added in response to that real failure, not pre-emptively."
|
||||
},
|
||||
{
|
||||
"command": "pre-commit run --files python_pkg/wsg_grabber/player.py python_pkg/wsg_grabber/_mpv_ipc.py python_pkg/wsg_grabber/_player_api.py",
|
||||
"result": "pass",
|
||||
"evidence": "Only the expected 'no staged evidence artifact' failure remained, which this file satisfies. ruff, ruff format, mypy, pylint, bandit and the coverage-gated pytest all pass with no suppression."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"_PROBE_ID is 9001 and read_reply matches replies on it. An intermediate version of the new module briefly carried a placeholder value of 1, which would have made every probe hang until timeout while still returning a plausible-looking error string; the constants were then moved across verbatim and the value re-checked at 9001.",
|
||||
"probe_properties/query now take an ipc_path rather than reading self._ipc_path. MpvPlayer.probe delegates, so the public behaviour is unchanged and the tests that drive mpv.probe() cover both."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; player.py returns to its 373-line form and the two new modules are deleted.",
|
||||
"After rollback, run python3 -m pytest python_pkg/wsg_grabber/tests/ -q to confirm 277 tests still pass."
|
||||
]
|
||||
}
|
||||
98
python_pkg/wsg_grabber/_fetch.py
Normal file
98
python_pkg/wsg_grabber/_fetch.py
Normal file
@ -0,0 +1,98 @@
|
||||
"""Fetching one claimed file and recording how it went.
|
||||
|
||||
Split out of :mod:`python_pkg.wsg_grabber.downloader` to keep it under the
|
||||
250-line cap. A mixin rather than free functions because the tests drive
|
||||
``worker._download_one()`` as a bound method and it shares the worker's
|
||||
download tally.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from python_pkg.wsg_grabber import catalog, net, scanner, store
|
||||
from python_pkg.wsg_grabber._worker_base import WorkerBase
|
||||
from python_pkg.wsg_grabber.models import Downloaded, FileReady, Outcome
|
||||
from python_pkg.wsg_grabber.states import FileEvent, FileState, next_state
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
from python_pkg.wsg_grabber.models import RemoteFile
|
||||
|
||||
|
||||
class DownloadMixin(WorkerBase):
|
||||
"""The file-fetching half of :class:`~.downloader.Worker`."""
|
||||
|
||||
def _download_one(self) -> None:
|
||||
"""Claim the next pending file and fetch it."""
|
||||
claimed = store.claim_next(self._deps.conn)
|
||||
if claimed is None:
|
||||
return
|
||||
part = (
|
||||
self._deps.incoming
|
||||
/ f"{store.local_name(claimed.md5, claimed.tim, claimed.ext)}.part"
|
||||
)
|
||||
self._wait_for_slot()
|
||||
result = net.download(
|
||||
self._deps.session,
|
||||
net.Transfer(
|
||||
url=catalog.media_url(claimed.tim, claimed.ext),
|
||||
part_path=part,
|
||||
expected_md5=claimed.md5,
|
||||
expected_size=claimed.fsize,
|
||||
should_stop=self._deps.stop.is_set,
|
||||
on_progress=lambda done: store.record_progress(
|
||||
self._deps.conn,
|
||||
claimed.md5,
|
||||
done,
|
||||
),
|
||||
),
|
||||
)
|
||||
self._apply_result(claimed, part, result.outcome, result.retry_after)
|
||||
|
||||
def _apply_result(
|
||||
self,
|
||||
claimed: RemoteFile,
|
||||
part: Path,
|
||||
outcome: Outcome,
|
||||
retry_after: float | None,
|
||||
) -> None:
|
||||
"""Translate a download outcome into index state and an event.
|
||||
|
||||
Args:
|
||||
claimed: The file that was attempted.
|
||||
part: Its partial-file path.
|
||||
outcome: How the download ended.
|
||||
retry_after: Server-requested pause, when supplied.
|
||||
"""
|
||||
if outcome is Outcome.ABORTED:
|
||||
store.set_state(self._deps.conn, claimed.md5, FileState.FAILED)
|
||||
return
|
||||
if outcome is Outcome.COMPLETED:
|
||||
final = part.with_suffix("")
|
||||
part.replace(final)
|
||||
store.mark_downloaded(self._deps.conn, claimed.md5, final.name)
|
||||
self._downloaded += 1
|
||||
self._publish(
|
||||
FileReady(
|
||||
item=store.ready_item(claimed, final),
|
||||
),
|
||||
)
|
||||
self._publish(Downloaded(count=self._downloaded))
|
||||
return
|
||||
|
||||
event = {
|
||||
Outcome.NOT_FOUND: FileEvent.NOT_FOUND,
|
||||
Outcome.CHECKSUM_MISMATCH: FileEvent.CHECKSUM_MISMATCH,
|
||||
Outcome.TRANSIENT: FileEvent.TRANSIENT_ERROR,
|
||||
}[outcome]
|
||||
attempts = store.attempts_for(self._deps.conn, claimed.md5)
|
||||
store.set_state(
|
||||
self._deps.conn,
|
||||
claimed.md5,
|
||||
next_state(FileState.DOWNLOADING, event, attempts),
|
||||
error=outcome.value,
|
||||
)
|
||||
if retry_after is not None:
|
||||
self._deps.stop.wait(scanner.backoff_seconds(attempts, retry_after))
|
||||
158
python_pkg/wsg_grabber/_mpv_ipc.py
Normal file
158
python_pkg/wsg_grabber/_mpv_ipc.py
Normal file
@ -0,0 +1,158 @@
|
||||
"""Talking to mpv: the command line, the wire format, and the reply reader.
|
||||
|
||||
Split out of :mod:`python_pkg.wsg_grabber.player` to keep it under the 250-line
|
||||
cap. Everything here is stateless -- it does not own the process or the socket,
|
||||
only the shapes of what goes over them.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import socket
|
||||
from typing import TYPE_CHECKING, Final
|
||||
|
||||
from python_pkg.wsg_grabber import logs
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
from pathlib import Path
|
||||
|
||||
_PROBE_ID = 9001
|
||||
_PROBE_TIMEOUT_S = 2.0
|
||||
|
||||
# What to record when diagnosing an apparently frozen reviewer: which file mpv
|
||||
# holds, whether it is actually advancing, and the size it configured its video
|
||||
# output to (which changes per video, so a static value is itself a symptom).
|
||||
_PROBE_PROPERTIES: Final[tuple[str, ...]] = (
|
||||
"path",
|
||||
"pause",
|
||||
"core-idle",
|
||||
"eof-reached",
|
||||
"playback-time",
|
||||
"width",
|
||||
"height",
|
||||
)
|
||||
|
||||
|
||||
def read_reply(conn: socket.socket) -> object:
|
||||
"""Read until mpv answers the probe request.
|
||||
|
||||
Args:
|
||||
conn: A freshly connected control socket.
|
||||
|
||||
Returns:
|
||||
object: The ``data`` field of the reply, or an ``error:`` string.
|
||||
"""
|
||||
buffer = b""
|
||||
while True:
|
||||
chunk = conn.recv(65536)
|
||||
if not chunk:
|
||||
return "error: socket closed"
|
||||
buffer += chunk
|
||||
for line in buffer.split(b"\n"):
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
message = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if message.get("request_id") == _PROBE_ID:
|
||||
return message.get("data")
|
||||
|
||||
|
||||
def build_argv(wid: int, ipc_path: Path) -> list[str]:
|
||||
"""Build the mpv command line.
|
||||
|
||||
``--input-vo-keyboard=no`` matters: with ``--wid`` mpv reparents a child
|
||||
window over the Tk frame, and if mpv claims the keyboard the Tk bindings
|
||||
never see a keypress. Declining it leaves X delivering keys to the focused
|
||||
toplevel, which is the Tk window.
|
||||
|
||||
Args:
|
||||
wid: X11 window id of the frame to draw into.
|
||||
ipc_path: Where to create the control socket.
|
||||
|
||||
Returns:
|
||||
list[str]: Argument vector for :func:`subprocess.Popen`.
|
||||
"""
|
||||
return [
|
||||
"mpv",
|
||||
f"--wid={wid}",
|
||||
f"--input-ipc-server={ipc_path}",
|
||||
"--idle=yes",
|
||||
"--loop-file=inf",
|
||||
"--keep-open=yes",
|
||||
"--no-terminal",
|
||||
"--osc=no",
|
||||
"--input-default-bindings=no",
|
||||
"--input-vo-keyboard=no",
|
||||
"--no-config",
|
||||
]
|
||||
|
||||
|
||||
def encode(command: Sequence[object]) -> bytes:
|
||||
"""Encode one mpv IPC command.
|
||||
|
||||
Args:
|
||||
command: Command name followed by its arguments.
|
||||
|
||||
Returns:
|
||||
bytes: Newline-terminated JSON, ready for the socket.
|
||||
"""
|
||||
return json.dumps({"command": list(command)}).encode("utf-8") + b"\n"
|
||||
|
||||
|
||||
def note_errors(chunk: bytes) -> None:
|
||||
"""Log any failure mpv reported back.
|
||||
|
||||
Args:
|
||||
chunk: Raw bytes just read from the socket.
|
||||
"""
|
||||
for line in chunk.split(b"\n"):
|
||||
if not line.strip():
|
||||
continue
|
||||
try:
|
||||
message = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
failure = message.get("error")
|
||||
if isinstance(failure, str) and failure != "success":
|
||||
logs.warning("player.reply_error", detail=failure, reply=message)
|
||||
|
||||
|
||||
def probe_properties(ipc_path: Path) -> dict[str, object]:
|
||||
"""Ask mpv for each diagnostic property in turn.
|
||||
|
||||
Args:
|
||||
ipc_path: Where mpv's control socket lives.
|
||||
|
||||
Returns:
|
||||
dict[str, object]: Property name to value; a property that could not
|
||||
be read maps to a string starting with ``error:``.
|
||||
"""
|
||||
return {name: query(ipc_path, name) for name in _PROBE_PROPERTIES}
|
||||
|
||||
|
||||
def query(ipc_path: Path, name: str) -> object:
|
||||
"""Read one mpv property over a short-lived connection.
|
||||
|
||||
A separate connection avoids interleaving with the asynchronous events mpv
|
||||
pushes down the main socket, which would otherwise make replies easy to
|
||||
mis-attribute.
|
||||
|
||||
Args:
|
||||
ipc_path: Where mpv's control socket lives.
|
||||
name: Property name.
|
||||
|
||||
Returns:
|
||||
object: The value, or an ``error:`` string.
|
||||
"""
|
||||
request = json.dumps({"command": ["get_property", name], "request_id": _PROBE_ID})
|
||||
try:
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as probe:
|
||||
probe.settimeout(_PROBE_TIMEOUT_S)
|
||||
probe.connect(str(ipc_path))
|
||||
probe.sendall(request.encode("utf-8") + b"\n")
|
||||
return read_reply(probe)
|
||||
except OSError as exc:
|
||||
return f"error: {exc}"
|
||||
49
python_pkg/wsg_grabber/_player_api.py
Normal file
49
python_pkg/wsg_grabber/_player_api.py
Normal file
@ -0,0 +1,49 @@
|
||||
"""What the reviewer window requires of a video player.
|
||||
|
||||
Split out of :mod:`python_pkg.wsg_grabber.player` to keep it under the 250-line
|
||||
cap. ``ui`` depends on this protocol rather than on :class:`~.player.MpvPlayer`,
|
||||
so the window can be driven by a stub in the tests without mpv present.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Protocol
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class Player(Protocol):
|
||||
"""What the reviewer needs from a video player."""
|
||||
|
||||
def play(self, path: Path) -> None:
|
||||
"""Show *path*, replacing whatever is on screen.
|
||||
|
||||
Args:
|
||||
path: Video file to play.
|
||||
"""
|
||||
... # pragma: no cover
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Blank the video area."""
|
||||
... # pragma: no cover
|
||||
|
||||
def is_alive(self) -> bool:
|
||||
"""Report whether the player is still running.
|
||||
|
||||
Returns:
|
||||
bool: True while the process lives.
|
||||
"""
|
||||
... # pragma: no cover
|
||||
|
||||
def probe(self) -> dict[str, object]:
|
||||
"""Report what the player is currently doing, for diagnostics.
|
||||
|
||||
Returns:
|
||||
dict[str, object]: Property name to value.
|
||||
"""
|
||||
... # pragma: no cover
|
||||
|
||||
def close(self) -> None:
|
||||
"""Shut the player down and release its resources."""
|
||||
... # pragma: no cover
|
||||
134
python_pkg/wsg_grabber/_scan.py
Normal file
134
python_pkg/wsg_grabber/_scan.py
Normal file
@ -0,0 +1,134 @@
|
||||
"""Walking the board: the thread list, the archive, and each changed thread.
|
||||
|
||||
Split out of :mod:`python_pkg.wsg_grabber.downloader` to keep it under the
|
||||
250-line cap. This is a mixin rather than a set of free functions because the
|
||||
tests drive these as bound methods (``worker._fetch_thread(...)``), and because
|
||||
they share the worker's scan bookkeeping.
|
||||
|
||||
The bare annotations below declare what ``Worker.__init__`` actually sets, so
|
||||
mypy can see the attributes without the mixin duplicating any of that state.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from python_pkg.wsg_grabber import catalog, scanner, store, store_threads
|
||||
from python_pkg.wsg_grabber._worker_base import WorkerBase
|
||||
from python_pkg.wsg_grabber.constants import (
|
||||
API_HOST,
|
||||
ARCHIVE_URL,
|
||||
BOARD,
|
||||
THREADS_URL,
|
||||
)
|
||||
from python_pkg.wsg_grabber.models import Indexed, ThreadRef
|
||||
from python_pkg.wsg_grabber.states import CLAIMABLE, FileState
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from python_pkg.wsg_grabber.models import JsonResponse
|
||||
|
||||
|
||||
class ScanMixin(WorkerBase):
|
||||
"""The board-walking half of :class:`~.downloader.Worker`."""
|
||||
|
||||
def _scan_step(self) -> None:
|
||||
"""Read the thread list, or fetch the next thread that changed."""
|
||||
if not self._catalog_fresh:
|
||||
self._refresh_thread_list()
|
||||
return
|
||||
ref = self._pending_threads.pop(0)
|
||||
self._fetch_thread(ref)
|
||||
|
||||
def _refresh_thread_list(self) -> None:
|
||||
"""Fetch ``threads.json`` and work out which threads to visit."""
|
||||
response = self._conditional_get(THREADS_URL)
|
||||
live = catalog.parse_thread_list(response.payload)
|
||||
if self._deps.include_archive:
|
||||
live = live + self._archive_refs()
|
||||
known = store_threads.known_threads(self._deps.conn)
|
||||
self._pending_threads = scanner.stale_threads(known, live)
|
||||
self._catalog_fresh = True
|
||||
self._finished_announced = False
|
||||
|
||||
def _archive_refs(self) -> list[ThreadRef]:
|
||||
"""Fetch the archive listing, tolerating boards without one.
|
||||
|
||||
Returns:
|
||||
list[ThreadRef]: Archived threads, empty when unavailable.
|
||||
"""
|
||||
response = self._conditional_get(ARCHIVE_URL)
|
||||
if response.not_found:
|
||||
return []
|
||||
return catalog.parse_archive(response.payload)
|
||||
|
||||
def _conditional_get(self, url: str) -> JsonResponse:
|
||||
"""Fetch a board-level endpoint, sending back the stamp we hold.
|
||||
|
||||
Without this an idle reviewer re-fetches threads.json and archive.json
|
||||
unconditionally every cycle. With it an unchanged board costs a 304.
|
||||
|
||||
Args:
|
||||
url: Absolute API URL.
|
||||
|
||||
Returns:
|
||||
JsonResponse: The response; on 304 the payload is None and the
|
||||
caller keeps whatever it already knew.
|
||||
"""
|
||||
stamp = store_threads.cached_last_modified(self._deps.conn, url)
|
||||
response = self._get_json(url, stamp)
|
||||
if not response.not_modified:
|
||||
store_threads.record_last_modified(
|
||||
self._deps.conn,
|
||||
url,
|
||||
response.last_modified,
|
||||
)
|
||||
return response
|
||||
|
||||
def _fetch_thread(self, ref: ThreadRef) -> None:
|
||||
"""Read one thread and record any files it introduces.
|
||||
|
||||
Args:
|
||||
ref: Thread to fetch.
|
||||
"""
|
||||
url = f"{API_HOST}/{BOARD}/thread/{ref.thread_no}.json"
|
||||
stamp = store_threads.http_last_modified(self._deps.conn, ref.thread_no)
|
||||
response = self._get_json(url, stamp)
|
||||
if response.not_found:
|
||||
store_threads.mark_thread_gone(self._deps.conn, ref.thread_no)
|
||||
return
|
||||
if response.not_modified:
|
||||
store_threads.record_thread(self._deps.conn, ref, stamp)
|
||||
return
|
||||
|
||||
parsed = catalog.parse_thread(ref.thread_no, response.payload)
|
||||
known = store.known_md5s(self._deps.conn)
|
||||
added = store.record_files(
|
||||
self._deps.conn,
|
||||
catalog.new_files(parsed, known),
|
||||
)
|
||||
self._write_off_deleted(catalog.deleted_md5s(response.payload), known)
|
||||
store_threads.record_thread(self._deps.conn, ref, response.last_modified)
|
||||
if added:
|
||||
self._publish(Indexed(known=len(known) + added))
|
||||
|
||||
def _write_off_deleted(self, gone: set[str], known: set[str]) -> None:
|
||||
"""Mark not-yet-fetched files terminal when the board drops them.
|
||||
|
||||
Only files still waiting to download are affected. Once the bytes are
|
||||
on disk the post being deleted upstream is irrelevant, so an already
|
||||
downloaded or reviewed file keeps its state -- the same rule the
|
||||
transition table encodes by rejecting ``READY + DELETED_UPSTREAM``.
|
||||
|
||||
Args:
|
||||
gone: md5s the board reports as deleted.
|
||||
known: md5s already in the index.
|
||||
"""
|
||||
for digest in gone & known:
|
||||
if store.state_of(self._deps.conn, digest) not in CLAIMABLE:
|
||||
continue
|
||||
store.set_state(
|
||||
self._deps.conn,
|
||||
digest,
|
||||
FileState.GONE,
|
||||
error="deleted upstream",
|
||||
)
|
||||
52
python_pkg/wsg_grabber/_worker_base.py
Normal file
52
python_pkg/wsg_grabber/_worker_base.py
Normal file
@ -0,0 +1,52 @@
|
||||
"""The state and collaborators the worker's two halves both rely on.
|
||||
|
||||
:class:`~python_pkg.wsg_grabber.downloader.Worker` is assembled from two mixins
|
||||
-- :mod:`._scan` and :mod:`._fetch` -- so that no single module exceeds the
|
||||
250-line cap. Each half touches bookkeeping the other half owns, so both
|
||||
inherit from here rather than declaring the same attributes twice.
|
||||
|
||||
The annotations carry no values: ``Worker.__init__`` remains the only place
|
||||
this state is created. The two methods are abstract because ``Worker`` supplies
|
||||
them; declaring them gives mypy and pylint something real to resolve against,
|
||||
which a bare mixin does not.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from python_pkg.wsg_grabber.downloader import WorkerDeps
|
||||
from python_pkg.wsg_grabber.models import (
|
||||
DownloadEvent,
|
||||
JsonResponse,
|
||||
ThreadRef,
|
||||
)
|
||||
|
||||
|
||||
class WorkerBase(ABC):
|
||||
"""State and collaborators shared by the worker's two halves."""
|
||||
|
||||
_deps: WorkerDeps
|
||||
_pending_threads: list[ThreadRef]
|
||||
_catalog_fresh: bool
|
||||
_finished_announced: bool
|
||||
|
||||
# Given a real class-level default rather than a bare annotation: _fetch
|
||||
# increments it (`self._downloaded += 1`), and pylint only treats an
|
||||
# attribute as existing for assignment when there is something to assign
|
||||
# to. Worker.__init__ still sets the instance value on construction.
|
||||
_downloaded: int = 0
|
||||
|
||||
@abstractmethod
|
||||
def _get_json(self, url: str, stamp: str | None = None) -> JsonResponse:
|
||||
"""Fetch a JSON endpoint, pacing requests and counting the last one."""
|
||||
|
||||
@abstractmethod
|
||||
def _publish(self, event: DownloadEvent) -> None:
|
||||
"""Hand an event to the UI thread."""
|
||||
|
||||
@abstractmethod
|
||||
def _wait_for_slot(self) -> None:
|
||||
"""Block until the polite inter-request delay has elapsed."""
|
||||
@ -21,32 +21,20 @@ from typing import TYPE_CHECKING
|
||||
|
||||
import requests
|
||||
|
||||
from python_pkg.wsg_grabber import catalog, net, scanner, store, store_threads
|
||||
from python_pkg.wsg_grabber import net, scanner, store
|
||||
from python_pkg.wsg_grabber._fetch import DownloadMixin
|
||||
from python_pkg.wsg_grabber._scan import ScanMixin
|
||||
from python_pkg.wsg_grabber.constants import (
|
||||
API_HOST,
|
||||
ARCHIVE_URL,
|
||||
BOARD,
|
||||
IDLE_POLL_S,
|
||||
IDLE_RESCAN_S,
|
||||
THREADS_URL,
|
||||
)
|
||||
from python_pkg.wsg_grabber.models import (
|
||||
Downloaded,
|
||||
FileReady,
|
||||
Indexed,
|
||||
JsonResponse,
|
||||
Outcome,
|
||||
ScanFinished,
|
||||
TaskKind,
|
||||
ThreadRef,
|
||||
WorkerFailed,
|
||||
)
|
||||
from python_pkg.wsg_grabber.states import (
|
||||
CLAIMABLE,
|
||||
FileEvent,
|
||||
FileState,
|
||||
next_state,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@ -71,7 +59,7 @@ if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
import queue
|
||||
|
||||
from python_pkg.wsg_grabber.models import DownloadEvent, RemoteFile
|
||||
from python_pkg.wsg_grabber.models import DownloadEvent
|
||||
|
||||
|
||||
@dataclass
|
||||
@ -86,8 +74,13 @@ class WorkerDeps:
|
||||
include_archive: bool = True
|
||||
|
||||
|
||||
class Worker:
|
||||
"""Walks /wsg/ and downloads every file it has not seen before."""
|
||||
class Worker(ScanMixin, DownloadMixin):
|
||||
"""Walks /wsg/ and downloads every file it has not seen before.
|
||||
|
||||
The board-walking and file-fetching halves live in _scan and _fetch to
|
||||
keep this module under the 250-line cap; they are mixins because the
|
||||
tests drive their methods as bound attributes of a Worker.
|
||||
"""
|
||||
|
||||
def __init__(self, deps: WorkerDeps) -> None:
|
||||
"""Store collaborators and initialise scan bookkeeping.
|
||||
@ -167,181 +160,6 @@ class Worker:
|
||||
self._catalog_fresh = False
|
||||
self._finished_announced = False
|
||||
|
||||
def _scan_step(self) -> None:
|
||||
"""Read the thread list, or fetch the next thread that changed."""
|
||||
if not self._catalog_fresh:
|
||||
self._refresh_thread_list()
|
||||
return
|
||||
ref = self._pending_threads.pop(0)
|
||||
self._fetch_thread(ref)
|
||||
|
||||
def _refresh_thread_list(self) -> None:
|
||||
"""Fetch ``threads.json`` and work out which threads to visit."""
|
||||
response = self._conditional_get(THREADS_URL)
|
||||
live = catalog.parse_thread_list(response.payload)
|
||||
if self._deps.include_archive:
|
||||
live = live + self._archive_refs()
|
||||
known = store_threads.known_threads(self._deps.conn)
|
||||
self._pending_threads = scanner.stale_threads(known, live)
|
||||
self._catalog_fresh = True
|
||||
self._finished_announced = False
|
||||
|
||||
def _archive_refs(self) -> list[ThreadRef]:
|
||||
"""Fetch the archive listing, tolerating boards without one.
|
||||
|
||||
Returns:
|
||||
list[ThreadRef]: Archived threads, empty when unavailable.
|
||||
"""
|
||||
response = self._conditional_get(ARCHIVE_URL)
|
||||
if response.not_found:
|
||||
return []
|
||||
return catalog.parse_archive(response.payload)
|
||||
|
||||
def _conditional_get(self, url: str) -> JsonResponse:
|
||||
"""Fetch a board-level endpoint, sending back the stamp we hold.
|
||||
|
||||
Without this an idle reviewer re-fetches threads.json and archive.json
|
||||
unconditionally every cycle. With it an unchanged board costs a 304.
|
||||
|
||||
Args:
|
||||
url: Absolute API URL.
|
||||
|
||||
Returns:
|
||||
JsonResponse: The response; on 304 the payload is None and the
|
||||
caller keeps whatever it already knew.
|
||||
"""
|
||||
stamp = store_threads.cached_last_modified(self._deps.conn, url)
|
||||
response = self._get_json(url, stamp)
|
||||
if not response.not_modified:
|
||||
store_threads.record_last_modified(
|
||||
self._deps.conn,
|
||||
url,
|
||||
response.last_modified,
|
||||
)
|
||||
return response
|
||||
|
||||
def _fetch_thread(self, ref: ThreadRef) -> None:
|
||||
"""Read one thread and record any files it introduces.
|
||||
|
||||
Args:
|
||||
ref: Thread to fetch.
|
||||
"""
|
||||
url = f"{API_HOST}/{BOARD}/thread/{ref.thread_no}.json"
|
||||
stamp = store_threads.http_last_modified(self._deps.conn, ref.thread_no)
|
||||
response = self._get_json(url, stamp)
|
||||
if response.not_found:
|
||||
store_threads.mark_thread_gone(self._deps.conn, ref.thread_no)
|
||||
return
|
||||
if response.not_modified:
|
||||
store_threads.record_thread(self._deps.conn, ref, stamp)
|
||||
return
|
||||
|
||||
parsed = catalog.parse_thread(ref.thread_no, response.payload)
|
||||
known = store.known_md5s(self._deps.conn)
|
||||
added = store.record_files(
|
||||
self._deps.conn,
|
||||
catalog.new_files(parsed, known),
|
||||
)
|
||||
self._write_off_deleted(catalog.deleted_md5s(response.payload), known)
|
||||
store_threads.record_thread(self._deps.conn, ref, response.last_modified)
|
||||
if added:
|
||||
self._publish(Indexed(known=len(known) + added))
|
||||
|
||||
def _write_off_deleted(self, gone: set[str], known: set[str]) -> None:
|
||||
"""Mark not-yet-fetched files terminal when the board drops them.
|
||||
|
||||
Only files still waiting to download are affected. Once the bytes are
|
||||
on disk the post being deleted upstream is irrelevant, so an already
|
||||
downloaded or reviewed file keeps its state -- the same rule the
|
||||
transition table encodes by rejecting ``READY + DELETED_UPSTREAM``.
|
||||
|
||||
Args:
|
||||
gone: md5s the board reports as deleted.
|
||||
known: md5s already in the index.
|
||||
"""
|
||||
for digest in gone & known:
|
||||
if store.state_of(self._deps.conn, digest) not in CLAIMABLE:
|
||||
continue
|
||||
store.set_state(
|
||||
self._deps.conn,
|
||||
digest,
|
||||
FileState.GONE,
|
||||
error="deleted upstream",
|
||||
)
|
||||
|
||||
def _download_one(self) -> None:
|
||||
"""Claim the next pending file and fetch it."""
|
||||
claimed = store.claim_next(self._deps.conn)
|
||||
if claimed is None:
|
||||
return
|
||||
part = (
|
||||
self._deps.incoming
|
||||
/ f"{store.local_name(claimed.md5, claimed.tim, claimed.ext)}.part"
|
||||
)
|
||||
self._wait_for_slot()
|
||||
result = net.download(
|
||||
self._deps.session,
|
||||
net.Transfer(
|
||||
url=catalog.media_url(claimed.tim, claimed.ext),
|
||||
part_path=part,
|
||||
expected_md5=claimed.md5,
|
||||
expected_size=claimed.fsize,
|
||||
should_stop=self._deps.stop.is_set,
|
||||
on_progress=lambda done: store.record_progress(
|
||||
self._deps.conn,
|
||||
claimed.md5,
|
||||
done,
|
||||
),
|
||||
),
|
||||
)
|
||||
self._apply_result(claimed, part, result.outcome, result.retry_after)
|
||||
|
||||
def _apply_result(
|
||||
self,
|
||||
claimed: RemoteFile,
|
||||
part: Path,
|
||||
outcome: Outcome,
|
||||
retry_after: float | None,
|
||||
) -> None:
|
||||
"""Translate a download outcome into index state and an event.
|
||||
|
||||
Args:
|
||||
claimed: The file that was attempted.
|
||||
part: Its partial-file path.
|
||||
outcome: How the download ended.
|
||||
retry_after: Server-requested pause, when supplied.
|
||||
"""
|
||||
if outcome is Outcome.ABORTED:
|
||||
store.set_state(self._deps.conn, claimed.md5, FileState.FAILED)
|
||||
return
|
||||
if outcome is Outcome.COMPLETED:
|
||||
final = part.with_suffix("")
|
||||
part.replace(final)
|
||||
store.mark_downloaded(self._deps.conn, claimed.md5, final.name)
|
||||
self._downloaded += 1
|
||||
self._publish(
|
||||
FileReady(
|
||||
item=store.ready_item(claimed, final),
|
||||
),
|
||||
)
|
||||
self._publish(Downloaded(count=self._downloaded))
|
||||
return
|
||||
|
||||
event = {
|
||||
Outcome.NOT_FOUND: FileEvent.NOT_FOUND,
|
||||
Outcome.CHECKSUM_MISMATCH: FileEvent.CHECKSUM_MISMATCH,
|
||||
Outcome.TRANSIENT: FileEvent.TRANSIENT_ERROR,
|
||||
}[outcome]
|
||||
attempts = store.attempts_for(self._deps.conn, claimed.md5)
|
||||
store.set_state(
|
||||
self._deps.conn,
|
||||
claimed.md5,
|
||||
next_state(FileState.DOWNLOADING, event, attempts),
|
||||
error=outcome.value,
|
||||
)
|
||||
if retry_after is not None:
|
||||
self._deps.stop.wait(scanner.backoff_seconds(attempts, retry_after))
|
||||
|
||||
def _announce_finished(self) -> None:
|
||||
"""Emit ScanFinished once per completed sweep of the board."""
|
||||
if self._finished_announced:
|
||||
|
||||
@ -19,16 +19,28 @@ orphan. No reviewing decisions are made here.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import socket
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from typing import TYPE_CHECKING, Final, Protocol
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from python_pkg.wsg_grabber import logs
|
||||
|
||||
# Re-exported through __all__ so player.Player / player.build_argv /
|
||||
# player.encode keep working for ui.py and test_player.py; the wire format and
|
||||
# the protocol live in their own modules to keep this one under the 250-line cap.
|
||||
from python_pkg.wsg_grabber._mpv_ipc import (
|
||||
build_argv,
|
||||
encode,
|
||||
note_errors,
|
||||
probe_properties,
|
||||
)
|
||||
from python_pkg.wsg_grabber._player_api import Player
|
||||
from python_pkg.wsg_grabber.constants import IPC_READY_TIMEOUT_S
|
||||
|
||||
__all__ = ["MpvPlayer", "Player", "build_argv", "encode"]
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
from pathlib import Path
|
||||
@ -37,125 +49,6 @@ _SOCKET_POLL_S = 0.05
|
||||
_READ_CHUNK = 65536
|
||||
_READ_TIMEOUT_S = 0.2
|
||||
_READER_JOIN_S = 5.0
|
||||
_PROBE_ID = 9001
|
||||
_PROBE_TIMEOUT_S = 2.0
|
||||
|
||||
# What to record when diagnosing an apparently frozen reviewer: which file mpv
|
||||
# holds, whether it is actually advancing, and the size it configured its video
|
||||
# output to (which changes per video, so a static value is itself a symptom).
|
||||
_PROBE_PROPERTIES: Final[tuple[str, ...]] = (
|
||||
"path",
|
||||
"pause",
|
||||
"core-idle",
|
||||
"eof-reached",
|
||||
"playback-time",
|
||||
"width",
|
||||
"height",
|
||||
)
|
||||
|
||||
|
||||
def _read_reply(conn: socket.socket) -> object:
|
||||
"""Read until mpv answers the probe request.
|
||||
|
||||
Args:
|
||||
conn: A freshly connected control socket.
|
||||
|
||||
Returns:
|
||||
object: The ``data`` field of the reply, or an ``error:`` string.
|
||||
"""
|
||||
buffer = b""
|
||||
while True:
|
||||
chunk = conn.recv(65536)
|
||||
if not chunk:
|
||||
return "error: socket closed"
|
||||
buffer += chunk
|
||||
for line in buffer.split(b"\n"):
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
message = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if message.get("request_id") == _PROBE_ID:
|
||||
return message.get("data")
|
||||
|
||||
|
||||
class Player(Protocol):
|
||||
"""What the reviewer needs from a video player."""
|
||||
|
||||
def play(self, path: Path) -> None:
|
||||
"""Show *path*, replacing whatever is on screen.
|
||||
|
||||
Args:
|
||||
path: Video file to play.
|
||||
"""
|
||||
... # pragma: no cover
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Blank the video area."""
|
||||
... # pragma: no cover
|
||||
|
||||
def is_alive(self) -> bool:
|
||||
"""Report whether the player is still running.
|
||||
|
||||
Returns:
|
||||
bool: True while the process lives.
|
||||
"""
|
||||
... # pragma: no cover
|
||||
|
||||
def probe(self) -> dict[str, object]:
|
||||
"""Report what the player is currently doing, for diagnostics.
|
||||
|
||||
Returns:
|
||||
dict[str, object]: Property name to value.
|
||||
"""
|
||||
... # pragma: no cover
|
||||
|
||||
def close(self) -> None:
|
||||
"""Shut the player down and release its resources."""
|
||||
... # pragma: no cover
|
||||
|
||||
|
||||
def build_argv(wid: int, ipc_path: Path) -> list[str]:
|
||||
"""Build the mpv command line.
|
||||
|
||||
``--input-vo-keyboard=no`` matters: with ``--wid`` mpv reparents a child
|
||||
window over the Tk frame, and if mpv claims the keyboard the Tk bindings
|
||||
never see a keypress. Declining it leaves X delivering keys to the focused
|
||||
toplevel, which is the Tk window.
|
||||
|
||||
Args:
|
||||
wid: X11 window id of the frame to draw into.
|
||||
ipc_path: Where to create the control socket.
|
||||
|
||||
Returns:
|
||||
list[str]: Argument vector for :func:`subprocess.Popen`.
|
||||
"""
|
||||
return [
|
||||
"mpv",
|
||||
f"--wid={wid}",
|
||||
f"--input-ipc-server={ipc_path}",
|
||||
"--idle=yes",
|
||||
"--loop-file=inf",
|
||||
"--keep-open=yes",
|
||||
"--no-terminal",
|
||||
"--osc=no",
|
||||
"--input-default-bindings=no",
|
||||
"--input-vo-keyboard=no",
|
||||
"--no-config",
|
||||
]
|
||||
|
||||
|
||||
def encode(command: Sequence[object]) -> bytes:
|
||||
"""Encode one mpv IPC command.
|
||||
|
||||
Args:
|
||||
command: Command name followed by its arguments.
|
||||
|
||||
Returns:
|
||||
bytes: Newline-terminated JSON, ready for the socket.
|
||||
"""
|
||||
return json.dumps({"command": list(command)}).encode("utf-8") + b"\n"
|
||||
|
||||
|
||||
class MpvPlayer:
|
||||
@ -228,19 +121,13 @@ class MpvPlayer:
|
||||
def _note_errors(self, chunk: bytes) -> None:
|
||||
"""Log any failure mpv reported back.
|
||||
|
||||
Delegates to :func:`._mpv_ipc.note_errors`; kept as a bound method
|
||||
because the reader thread and the tests both reach it that way.
|
||||
|
||||
Args:
|
||||
chunk: Raw bytes just read from the socket.
|
||||
"""
|
||||
for line in chunk.split(b"\n"):
|
||||
if not line.strip():
|
||||
continue
|
||||
try:
|
||||
message = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
failure = message.get("error")
|
||||
if isinstance(failure, str) and failure != "success":
|
||||
logs.warning("player.reply_error", detail=failure, reply=message)
|
||||
note_errors(chunk)
|
||||
|
||||
def _connect(self) -> socket.socket:
|
||||
"""Wait for mpv's socket to appear and connect to it.
|
||||
@ -319,32 +206,7 @@ class MpvPlayer:
|
||||
dict[str, object]: Property name to value; a property that could
|
||||
not be read maps to a string starting with ``error:``.
|
||||
"""
|
||||
return {name: self._query(name) for name in _PROBE_PROPERTIES}
|
||||
|
||||
def _query(self, name: str) -> object:
|
||||
"""Read one mpv property over a short-lived connection.
|
||||
|
||||
A separate connection avoids interleaving with the asynchronous events
|
||||
mpv pushes down the main socket, which would otherwise make replies
|
||||
easy to mis-attribute.
|
||||
|
||||
Args:
|
||||
name: Property name.
|
||||
|
||||
Returns:
|
||||
object: The value, or an ``error:`` string.
|
||||
"""
|
||||
request = json.dumps(
|
||||
{"command": ["get_property", name], "request_id": _PROBE_ID}
|
||||
)
|
||||
try:
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as probe:
|
||||
probe.settimeout(_PROBE_TIMEOUT_S)
|
||||
probe.connect(str(self._ipc_path))
|
||||
probe.sendall(request.encode("utf-8") + b"\n")
|
||||
return _read_reply(probe)
|
||||
except OSError as exc:
|
||||
return f"error: {exc}"
|
||||
return probe_properties(self._ipc_path)
|
||||
|
||||
def is_alive(self) -> bool:
|
||||
"""Report whether mpv is still running.
|
||||
|
||||
@ -91,6 +91,44 @@ Verified on `wsg_grabber/cli.py`; `__all__` passes ruff + mypy + pylint clean.
|
||||
Splits that only move **private** helpers (leading `_`, no external caller)
|
||||
need no shim at all — check with grep first, as in `catalog.py`.
|
||||
|
||||
`__all__` only needs the **re-exported** names, not every public name in the
|
||||
module — names defined locally stay reachable either way. Verified against the
|
||||
full gate on `store.py`. Worth ~5–8 lines on every file with this shape, which
|
||||
matters: three splits so far landed 2–6 lines over the cap and needed a second
|
||||
seam. **Budget the new import block and `__all__` before deciding a two-way
|
||||
split is enough.**
|
||||
|
||||
Splitting a **class**: if tests call private methods as bound attributes
|
||||
(`worker._fetch_thread(...)` — grep the tests first), module-level functions
|
||||
will not do; use mixins. The shape that passes every gate with **no
|
||||
suppression** (settled on `downloader.py`, do not re-derive):
|
||||
|
||||
```python
|
||||
# _worker_base.py
|
||||
class WorkerBase(ABC):
|
||||
_deps: WorkerDeps # bare annotations for read-only attributes
|
||||
_downloaded: int = 0 # real default for any attribute the mixin ASSIGNS
|
||||
|
||||
@abstractmethod
|
||||
def _publish(self, event: DownloadEvent) -> None:
|
||||
"""Supplied by the concrete Worker."""
|
||||
```
|
||||
|
||||
Both mixins inherit `WorkerBase`; `Worker(ScanMixin, DownloadMixin)`. Why not
|
||||
the obvious alternatives:
|
||||
|
||||
- Naming a class `*Mixin` does **not** get you pylint's `no-member` exemption
|
||||
here — `ignored-checks-for-mixins` is not configured for it. Don't rely on it.
|
||||
- `raise NotImplementedError` stub bodies are **uncovered lines** under the
|
||||
100% branch gate.
|
||||
- `if TYPE_CHECKING: def _publish(...) -> None: ...` satisfies mypy but leaves
|
||||
pylint reporting `no-member`.
|
||||
- A bare annotation (`_downloaded: int`) is not enough for an attribute the
|
||||
mixin assigns to (`+= 1`); pylint wants a real default.
|
||||
|
||||
Watch the MRO: `Worker(ScanMixin, DownloadMixin)` means ScanMixin wins any
|
||||
name collision.
|
||||
|
||||
Coverage: `meta/pyproject.toml` sets `source = ["python_pkg"]`, so a new
|
||||
sibling module is measured automatically. Confirmed: new modules show up in
|
||||
the report at 100% rather than being silently skipped. Add no new branches
|
||||
@ -110,6 +148,23 @@ the report at 100% rather than being silently skipped. Add no new branches
|
||||
Never game the cap: no one-lining, no deleting tests, no moving code into an
|
||||
exempt extension, no suppressions.
|
||||
|
||||
## Never edit files while a push is running
|
||||
|
||||
`git push` runs pre-commit, which **stashes unstaged changes and restores them
|
||||
afterwards**. Editing a file in that window makes the restore fail with
|
||||
`patch does not apply`, and the push aborts — _while `git push | tail` still
|
||||
reports exit 0_, because the pipe masks it. This cost two silent failed pushes
|
||||
and one silently reverted split.
|
||||
|
||||
Rules that follow:
|
||||
|
||||
- Stage (`git add`) before running `pre-commit run --files ...` on a
|
||||
work-in-progress tree, or the same stash cycle can revert the edit.
|
||||
- Push only with a clean tree, and do not start other file edits until it
|
||||
returns.
|
||||
- After any push, confirm with `git status --short --branch` that it does not
|
||||
still say `ahead N`. Never trust the exit code alone.
|
||||
|
||||
## Traps that cost time in the last session
|
||||
|
||||
- **Test fixtures and coverage.** When splitting a test file, shared helpers
|
||||
|
||||
Loading…
Reference in New Issue
Block a user