mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-24 21:46:28 +01:00
Compare commits
10 Commits
9d6829a0ee
...
44b80ee6cf
| Author | SHA1 | Date | |
|---|---|---|---|
| 44b80ee6cf | |||
| 1869fdee02 | |||
| 4531be3870 | |||
| db2650b9c9 | |||
| 65e72d8ded | |||
| 1194517702 | |||
| c29d0989dd | |||
| f21bfa7a5b | |||
| de9d41d6f0 | |||
| a9342e63e1 |
71
.github/workflows/game-recording-precommit.yml
vendored
Normal file
71
.github/workflows/game-recording-precommit.yml
vendored
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
name: game_recording pre-commit
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
# The workflow's own file counts as game_recording: editing only this file used
|
||||||
|
# to trigger nothing, so a fix to the job itself could never prove itself.
|
||||||
|
paths: ['game_recording/**', '.github/workflows/game-recording-precommit.yml']
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
paths: ['game_recording/**', '.github/workflows/game-recording-precommit.yml']
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
pre-commit:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: "3.x"
|
||||||
|
# Only pre-commit itself. Every linting hook runs in its own isolated
|
||||||
|
# env -- ruff, mypy, pylint, bandit and codespell each come from their
|
||||||
|
# own repo+rev, and the local hooks need nothing beyond bash and
|
||||||
|
# python3 -- so installing the full requirements.txt spent 9s a run on
|
||||||
|
# packages no pre-commit-stage hook imports. Verified by running this
|
||||||
|
# package's config green in a venv holding pre-commit and nothing else.
|
||||||
|
# The pin is read out of requirements.txt rather than repeated here, so
|
||||||
|
# it cannot drift from what the dependency-freshness gate governs.
|
||||||
|
- name: Install pre-commit
|
||||||
|
run: |
|
||||||
|
pip install "$(grep '^pre-commit==' game_recording/requirements.txt)"
|
||||||
|
|
||||||
|
# Keyed on THIS package's config. pre-commit/action@v3.0.1 caches on
|
||||||
|
# hashFiles('.pre-commit-config.yaml') -- the repo ROOT's -- so editing
|
||||||
|
# this package's config would not invalidate it, and other jobs in the
|
||||||
|
# repo that cache hooks under that key could overwrite it with a
|
||||||
|
# different hook set. A key from this config cannot go stale that way.
|
||||||
|
- uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: ~/.cache/pre-commit
|
||||||
|
key: >-
|
||||||
|
pre-commit-game-recording-${{ env.pythonLocation }}-${{
|
||||||
|
hashFiles('game_recording/.pre-commit-config.yaml') }}
|
||||||
|
# Prefix fallback, or this fix would evaporate on the very
|
||||||
|
# event that motivated it: bumping a hook rev changes the
|
||||||
|
# exact key, and a total miss means reinstalling every hook
|
||||||
|
# again. pre-commit's store is keyed internally by hook
|
||||||
|
# repo+rev, so a superseded entry is ignored disk rather
|
||||||
|
# than a wrong hook, and cache still re-saves under the new
|
||||||
|
# exact key after a prefix-only hit.
|
||||||
|
restore-keys: pre-commit-game-recording-${{ env.pythonLocation }}-
|
||||||
|
# mypy re-analyses the stdlib and every third-party stub from scratch
|
||||||
|
# without this, which measured 10s of the hook step in CI against 0.25s
|
||||||
|
# warm locally -- a 19MB cache dir does the whole difference. Keyed on
|
||||||
|
# the config, not the sources: mypy's own cache metadata records the
|
||||||
|
# interpreter, the flag set and a hash per source file, so it re-checks
|
||||||
|
# what changed and cannot pass stale code. Deliberately NOT keyed on
|
||||||
|
# github.sha -- that re-saves 19MB every commit and would evict the
|
||||||
|
# 68MB hook caches under the repo's 10GB LRU budget. A fixed key keeps
|
||||||
|
# the expensive part, the dependency analysis, which is what costs 10s.
|
||||||
|
- uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: .mypy_cache
|
||||||
|
key: >-
|
||||||
|
mypy-game-recording-${{ env.pythonLocation }}-${{
|
||||||
|
hashFiles('game_recording/.pre-commit-config.yaml') }}
|
||||||
|
restore-keys: mypy-game-recording-${{ env.pythonLocation }}-
|
||||||
|
- name: Run the hooks
|
||||||
|
run: >-
|
||||||
|
pre-commit run --config game_recording/.pre-commit-config.yaml
|
||||||
|
--all-files --show-diff-on-failure
|
||||||
35
.github/workflows/game-recording-tests.yml
vendored
Normal file
35
.github/workflows/game-recording-tests.yml
vendored
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
name: game_recording tests
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
# The workflow's own file counts as game_recording: editing only this file used
|
||||||
|
# to trigger nothing, so a fix to the job itself could never prove itself.
|
||||||
|
paths: ['game_recording/**', '.github/workflows/game-recording-tests.yml']
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
paths: ['game_recording/**', '.github/workflows/game-recording-tests.yml']
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: game_recording
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Python
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: "3.x"
|
||||||
|
|
||||||
|
# The finalize and library tests run the real ffmpeg and ffprobe.
|
||||||
|
- name: Install ffmpeg
|
||||||
|
run: sudo apt-get update && sudo apt-get install -y ffmpeg
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: pip install -r requirements.txt
|
||||||
|
|
||||||
|
- name: Run tests with coverage
|
||||||
|
run: python -m pytest -v --cov=game_recording
|
||||||
38
.github/workflows/godot-dev-tools-tests.yml
vendored
Normal file
38
.github/workflows/godot-dev-tools-tests.yml
vendored
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
name: godot_dev_tools tests
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
paths: ['godot_dev_tools/**', '.github/workflows/godot-dev-tools-tests.yml']
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
paths: ['godot_dev_tools/**', '.github/workflows/godot-dev-tools-tests.yml']
|
||||||
|
|
||||||
|
env:
|
||||||
|
GODOT_VERSION: "4.7.2"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: actions/setup-python@v5
|
||||||
|
with: { python-version: "3.15.2" }
|
||||||
|
|
||||||
|
- name: Install Godot
|
||||||
|
run: |
|
||||||
|
curl -fsSL -o godot.zip "https://github.com/godotengine/godot/releases/download/${GODOT_VERSION}-stable/Godot_v${GODOT_VERSION}-stable_linux.x86_64.zip"
|
||||||
|
unzip -q godot.zip
|
||||||
|
chmod +x "Godot_v${GODOT_VERSION}-stable_linux.x86_64"
|
||||||
|
sudo mv "Godot_v${GODOT_VERSION}-stable_linux.x86_64" /usr/local/bin/godot
|
||||||
|
rm godot.zip
|
||||||
|
|
||||||
|
- name: Install gdtoolkit (pinned)
|
||||||
|
run: pip install -r godot_dev_tools/requirements-dev.txt
|
||||||
|
|
||||||
|
- name: Lint (gdlint, gdformat)
|
||||||
|
run: godot_dev_tools/lint.sh
|
||||||
|
|
||||||
|
- name: GUT against the stub host (GUT is fetched at its pinned tag)
|
||||||
|
run: godot_dev_tools/test.sh
|
||||||
2
.github/workflows/ts-config-tests.yml
vendored
2
.github/workflows/ts-config-tests.yml
vendored
@ -25,7 +25,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: "24.22.1"
|
node-version: "26.13.1"
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: pnpm install --frozen-lockfile
|
run: pnpm install --frozen-lockfile
|
||||||
|
|||||||
2
.github/workflows/ts-core-tests.yml
vendored
2
.github/workflows/ts-core-tests.yml
vendored
@ -25,7 +25,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: "24.22.1"
|
node-version: "26.13.1"
|
||||||
|
|
||||||
# The preset is a `link:../ts_config` dependency. pnpm links the
|
# The preset is a `link:../ts_config` dependency. pnpm links the
|
||||||
# directory but installs nothing inside it, and a flat config imports
|
# directory but installs nothing inside it, and a flat config imports
|
||||||
|
|||||||
2
.github/workflows/web-ui-tests.yml
vendored
2
.github/workflows/web-ui-tests.yml
vendored
@ -25,7 +25,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: "24.22.1"
|
node-version: "26.13.1"
|
||||||
|
|
||||||
# The preset is a `link:../ts_config` dependency. pnpm links the
|
# The preset is a `link:../ts_config` dependency. pnpm links the
|
||||||
# directory but installs nothing inside it, and a flat config imports
|
# directory but installs nothing inside it, and a flat config imports
|
||||||
|
|||||||
@ -1,8 +1,9 @@
|
|||||||
# utils
|
# utils
|
||||||
|
|
||||||
Monorepo of shared gates and libraries (dep_freshness, file_length, md_naming,
|
Monorepo of shared gates and libraries (dep_freshness, file_length, md_naming,
|
||||||
repo_contract, coverage_gaps, crdt-sync, gatelock, freedays, sickdays, earned_time, music_theory,
|
repo_contract, coverage_gaps, crdt-sync, gatelock, freedays, sickdays, earned_time, music_theory, game_recording,
|
||||||
flutter_web_drive (headless Flutter-web E2E driver + MCP), ...).
|
flutter_web_drive (headless Flutter-web E2E driver + MCP), ...).
|
||||||
|
`godot_dev_tools/` is a Godot addon (GDScript): `godot_dev_tools/test.sh` runs its GUT tests.
|
||||||
Python packages with a root-level `<pkg>/tests` run with `PYTHONPATH=.`;
|
Python packages with a root-level `<pkg>/tests` run with `PYTHONPATH=.`;
|
||||||
subprojects with their own `pyproject.toml` run via `scripts/run_subproject_tests.sh <dir>`.
|
subprojects with their own `pyproject.toml` run via `scripts/run_subproject_tests.sh <dir>`.
|
||||||
`scripts/check_repo_contract.sh` is the REAL shared gate (not a shim): never
|
`scripts/check_repo_contract.sh` is the REAL shared gate (not a shim): never
|
||||||
|
|||||||
24
README.md
24
README.md
@ -101,6 +101,17 @@ Consume via:
|
|||||||
music_theory @ git+https://github.com/kuhyx/utils@music-theory-v0.1.0#subdirectory=music_theory
|
music_theory @ git+https://github.com/kuhyx/utils@music-theory-v0.1.0#subdirectory=music_theory
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## game_recording/
|
||||||
|
|
||||||
|
Session recorder for a game (package: `game_recording`, stdlib only, not
|
||||||
|
published to PyPI): records a dev run from outside the game and stamps its
|
||||||
|
telemetry moments onto the video. A game configures it with one `Config`.
|
||||||
|
|
||||||
|
Consume via:
|
||||||
|
```
|
||||||
|
game_recording @ git+https://github.com/kuhyx/utils@game-recording-v0.1.0#subdirectory=game_recording
|
||||||
|
```
|
||||||
|
|
||||||
## unified-design-system/
|
## unified-design-system/
|
||||||
|
|
||||||
Not a package — the frozen design tokens (colors, spacing, type, radius,
|
Not a package — the frozen design tokens (colors, spacing, type, radius,
|
||||||
@ -128,3 +139,16 @@ planted violation per rule family proves each gate bites.
|
|||||||
"@kuhyx/ts-config": "github:kuhyx/utils#ts_config-v0.1.0&path:/ts_config"
|
"@kuhyx/ts-config": "github:kuhyx/utils#ts_config-v0.1.0&path:/ts_config"
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## godot_dev_tools/
|
||||||
|
|
||||||
|
Godot addon (`addons/dev_tools/`): the F12 dev feedback mode of kuhy's games
|
||||||
|
(annotate the frozen frame, save a bundle that `feedback_inbox` turns into a
|
||||||
|
task). A game mounts it at a pinned tag; the game's own code stays a small host
|
||||||
|
object. Read [`godot_dev_tools/README.md`](godot_dev_tools/README.md).
|
||||||
|
|
||||||
|
Consume via a shallow fetch of the tag, then mount the addon folder:
|
||||||
|
```
|
||||||
|
git clone --depth 1 --branch godot-dev-tools-v0.1.1 https://github.com/kuhyx/utils
|
||||||
|
# link or copy godot_dev_tools/addons/dev_tools to res://addons/dev_tools
|
||||||
|
```
|
||||||
|
|||||||
@ -103,14 +103,19 @@ repos:
|
|||||||
- --disable-error-code=list-item
|
- --disable-error-code=list-item
|
||||||
|
|
||||||
- repo: https://github.com/pylint-dev/pylint
|
- repo: https://github.com/pylint-dev/pylint
|
||||||
rev: v4.0.8
|
rev: v4.1.4
|
||||||
hooks:
|
hooks:
|
||||||
- id: pylint
|
- id: pylint
|
||||||
args:
|
args:
|
||||||
- --rcfile=crdt-sync/pyproject.toml
|
- --rcfile=crdt-sync/pyproject.toml
|
||||||
- --fail-under=10
|
- --fail-under=10
|
||||||
- --jobs=4
|
# One process: with --jobs>1 pylint pickles its AST via dill, which
|
||||||
|
# dies on Python 3.15 (code objects lost co_lnotab), 2026-11-16.
|
||||||
|
- --jobs=1
|
||||||
additional_dependencies:
|
additional_dependencies:
|
||||||
|
# Kept in step with pyproject.toml, so pylint resolves the e2e imports.
|
||||||
|
- argon2-cffi==25.1.0
|
||||||
|
- pynacl==1.6.2
|
||||||
- pytest
|
- pytest
|
||||||
- requests
|
- requests
|
||||||
|
|
||||||
|
|||||||
32
crdt-sync/crdt_sync/_e2e_blobs.py
Normal file
32
crdt-sync/crdt_sync/_e2e_blobs.py
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""Read every text blob under an old (plaintext) prefix, for the e2e copy."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from crdt_sync._sync import default_revs_path
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from crdt_sync._remote import RemoteStore
|
||||||
|
|
||||||
|
|
||||||
|
def blobs(store: RemoteStore, root: str) -> dict[str, str]:
|
||||||
|
"""Every text blob under ``root`` (flat leaves and ``<dir>/<file>``)."""
|
||||||
|
skip = {default_revs_path(root), f"{root}/e2e", f"{root}/revs"}
|
||||||
|
out: dict[str, str] = {}
|
||||||
|
for name in store.list_directory(root):
|
||||||
|
full = f"{root}/{name}"
|
||||||
|
if full in skip:
|
||||||
|
continue
|
||||||
|
children = store.list_directory(full)
|
||||||
|
if not children:
|
||||||
|
text = store.get_file_text(full)
|
||||||
|
if text is not None:
|
||||||
|
out[name] = text
|
||||||
|
continue
|
||||||
|
for child in children:
|
||||||
|
text = store.get_file_text(f"{full}/{child}")
|
||||||
|
if text is not None:
|
||||||
|
out[f"{name}/{child}"] = text
|
||||||
|
return out
|
||||||
@ -12,8 +12,9 @@ from __future__ import annotations
|
|||||||
import hmac
|
import hmac
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from crdt_sync._e2e_blobs import blobs as _blobs
|
||||||
from crdt_sync._e2e_key import derive_key, read_header
|
from crdt_sync._e2e_key import derive_key, read_header
|
||||||
from crdt_sync._e2e_store import E2eLayout, E2eLockedError, EncryptingStore, _blobs
|
from crdt_sync._e2e_store import E2eLayout, E2eLockedError, EncryptingStore
|
||||||
from crdt_sync._log import merge_logs
|
from crdt_sync._log import merge_logs
|
||||||
from crdt_sync._store import dump_log, load_log
|
from crdt_sync._store import dump_log, load_log
|
||||||
|
|
||||||
|
|||||||
@ -97,6 +97,7 @@ class _Header:
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def parse(cls, text: str) -> _Header:
|
def parse(cls, text: str) -> _Header:
|
||||||
|
"""Read a header from its JSON text; ``E2eHeaderError`` if it is not one."""
|
||||||
try:
|
try:
|
||||||
data = json.loads(text)
|
data = json.loads(text)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
@ -119,6 +120,7 @@ class _Header:
|
|||||||
raise E2eHeaderError(msg) from exc
|
raise E2eHeaderError(msg) from exc
|
||||||
|
|
||||||
def encode(self) -> str:
|
def encode(self) -> str:
|
||||||
|
"""The header as the JSON text ``parse`` reads back."""
|
||||||
return json.dumps(
|
return json.dumps(
|
||||||
{
|
{
|
||||||
"v": _HEADER_VERSION,
|
"v": _HEADER_VERSION,
|
||||||
|
|||||||
@ -12,6 +12,7 @@ from dataclasses import dataclass
|
|||||||
import logging
|
import logging
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from crdt_sync._e2e_blobs import blobs as _blobs
|
||||||
from crdt_sync._e2e_cache import (
|
from crdt_sync._e2e_cache import (
|
||||||
read_cached_key,
|
read_cached_key,
|
||||||
read_copy_memo,
|
read_copy_memo,
|
||||||
@ -126,27 +127,6 @@ class EncryptingStore:
|
|||||||
return self._inner.can_access_remote()
|
return self._inner.can_access_remote()
|
||||||
|
|
||||||
|
|
||||||
def _blobs(store: RemoteStore, root: str) -> dict[str, str]:
|
|
||||||
"""Every text blob under ``root`` (flat leaves and ``<dir>/<file>``)."""
|
|
||||||
skip = {default_revs_path(root), f"{root}/e2e", f"{root}/revs"}
|
|
||||||
out: dict[str, str] = {}
|
|
||||||
for name in store.list_directory(root):
|
|
||||||
full = f"{root}/{name}"
|
|
||||||
if full in skip:
|
|
||||||
continue
|
|
||||||
children = store.list_directory(full)
|
|
||||||
if not children:
|
|
||||||
text = store.get_file_text(full)
|
|
||||||
if text is not None:
|
|
||||||
out[name] = text
|
|
||||||
continue
|
|
||||||
for child in children:
|
|
||||||
text = store.get_file_text(f"{full}/{child}")
|
|
||||||
if text is not None:
|
|
||||||
out[f"{name}/{child}"] = text
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def copy_to_encrypted(
|
def copy_to_encrypted(
|
||||||
store: RemoteStore, key: E2eKey, old_prefix: str, layout: E2eLayout
|
store: RemoteStore, key: E2eKey, old_prefix: str, layout: E2eLayout
|
||||||
) -> int:
|
) -> int:
|
||||||
|
|||||||
@ -20,7 +20,8 @@ from crdt_sync import (
|
|||||||
reset_e2e_copy_memo,
|
reset_e2e_copy_memo,
|
||||||
unlock_e2e,
|
unlock_e2e,
|
||||||
)
|
)
|
||||||
from crdt_sync._e2e_store import _blobs, _fingerprint
|
from crdt_sync._e2e_blobs import blobs as _blobs
|
||||||
|
from crdt_sync._e2e_store import _fingerprint
|
||||||
from crdt_sync.tests.conftest import FakeStore, FakeStoreWithoutBulkRead
|
from crdt_sync.tests.conftest import FakeStore, FakeStoreWithoutBulkRead
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
|
|||||||
@ -108,8 +108,9 @@ ignore-patterns = [".*\\.pyi$"]
|
|||||||
[tool.pylint.basic]
|
[tool.pylint.basic]
|
||||||
# snake_case, plus the ``do_<METHOD>`` names http.server dispatches on: the
|
# snake_case, plus the ``do_<METHOD>`` names http.server dispatches on: the
|
||||||
# stdlib looks handlers up as ``"do_" + command``, so ``do_GET`` is the only
|
# stdlib looks handlers up as ``"do_" + command``, so ``do_GET`` is the only
|
||||||
# spelling that works and cannot be renamed to satisfy the style.
|
# spelling that works and cannot be renamed to satisfy the style. ``of`` is
|
||||||
method-rgx = "([^\\W\\dA-Z][^\\WA-Z]{2,}|_[^\\WA-Z]*|__[^\\W\\dA-Z][^\\WA-Z]+__|do_[A-Z]+)$"
|
# ``E2eLayout.of``, public API that daily-limits and diet-guard call by name.
|
||||||
|
method-rgx = "([^\\W\\dA-Z][^\\WA-Z]{2,}|_[^\\WA-Z]*|__[^\\W\\dA-Z][^\\WA-Z]+__|do_[A-Z]+|of)$"
|
||||||
|
|
||||||
[tool.pylint.messages_control]
|
[tool.pylint.messages_control]
|
||||||
enable = "all"
|
enable = "all"
|
||||||
|
|||||||
@ -5,10 +5,10 @@ argon2-cffi==25.1.0
|
|||||||
bandit[toml]==1.9.4
|
bandit[toml]==1.9.4
|
||||||
mypy==2.4.1
|
mypy==2.4.1
|
||||||
pre-commit==4.7.0
|
pre-commit==4.7.0
|
||||||
pylint==4.1.3
|
pylint==4.1.4
|
||||||
pynacl==1.6.2
|
pynacl==1.6.2
|
||||||
pytest==9.2.0
|
pytest==9.2.0
|
||||||
pytest-cov==7.1.0
|
pytest-cov==7.1.0
|
||||||
requests==2.34.2
|
requests==2.34.2
|
||||||
ruff==0.17.4
|
ruff==0.17.5
|
||||||
types-requests==2.33.0.20261030
|
types-requests==2.33.0.20261030
|
||||||
|
|||||||
@ -4,44 +4,15 @@ import 'dart:math';
|
|||||||
import 'package:cryptography/cryptography.dart';
|
import 'package:cryptography/cryptography.dart';
|
||||||
|
|
||||||
import 'e2e_cipher.dart';
|
import 'e2e_cipher.dart';
|
||||||
|
import 'e2e_params.dart';
|
||||||
import 'encrypting_store.dart';
|
import 'encrypting_store.dart';
|
||||||
import 'remote_store.dart';
|
import 'remote_store.dart';
|
||||||
|
|
||||||
|
export 'e2e_params.dart';
|
||||||
|
|
||||||
const _saltLength = 16;
|
const _saltLength = 16;
|
||||||
const _headerVersion = 1;
|
const _headerVersion = 1;
|
||||||
|
|
||||||
/// Argon2id cost, stored in the header so it can be raised later.
|
|
||||||
class Argon2Params {
|
|
||||||
const Argon2Params({
|
|
||||||
required this.memoryKiB,
|
|
||||||
required this.iterations,
|
|
||||||
required this.parallelism,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// OWASP's floor (19 MiB, t=2); higher stalls the Flutter-web desktop build.
|
|
||||||
static const recommended = Argon2Params(
|
|
||||||
memoryKiB: 19456,
|
|
||||||
iterations: 2,
|
|
||||||
parallelism: 1,
|
|
||||||
);
|
|
||||||
|
|
||||||
final int memoryKiB;
|
|
||||||
final int iterations;
|
|
||||||
final int parallelism;
|
|
||||||
}
|
|
||||||
|
|
||||||
class E2eHeaderError extends FormatException {
|
|
||||||
E2eHeaderError(super.message);
|
|
||||||
|
|
||||||
@override
|
|
||||||
String toString() => 'E2eHeaderError: $message';
|
|
||||||
}
|
|
||||||
|
|
||||||
class E2eWrongPassphraseError implements Exception {
|
|
||||||
@override
|
|
||||||
String toString() => 'E2eWrongPassphraseError: wrong sync passphrase';
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The clear header's path: a sibling of the device dirs, like `revs`.
|
/// The clear header's path: a sibling of the device dirs, like `revs`.
|
||||||
String defaultE2ePath(String pathPrefix) {
|
String defaultE2ePath(String pathPrefix) {
|
||||||
final cut = pathPrefix.lastIndexOf('/');
|
final cut = pathPrefix.lastIndexOf('/');
|
||||||
|
|||||||
34
crdt_sync_dart/lib/src/e2e_params.dart
Normal file
34
crdt_sync_dart/lib/src/e2e_params.dart
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
/// The e2e header's Argon2id cost and the errors unlocking it can raise.
|
||||||
|
library;
|
||||||
|
|
||||||
|
/// Argon2id cost, stored in the header so it can be raised later.
|
||||||
|
class Argon2Params {
|
||||||
|
const Argon2Params({
|
||||||
|
required this.memoryKiB,
|
||||||
|
required this.iterations,
|
||||||
|
required this.parallelism,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// OWASP's floor (19 MiB, t=2); higher stalls the Flutter-web desktop build.
|
||||||
|
static const recommended = Argon2Params(
|
||||||
|
memoryKiB: 19456,
|
||||||
|
iterations: 2,
|
||||||
|
parallelism: 1,
|
||||||
|
);
|
||||||
|
|
||||||
|
final int memoryKiB;
|
||||||
|
final int iterations;
|
||||||
|
final int parallelism;
|
||||||
|
}
|
||||||
|
|
||||||
|
class E2eHeaderError extends FormatException {
|
||||||
|
E2eHeaderError(super.message);
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => 'E2eHeaderError: $message';
|
||||||
|
}
|
||||||
|
|
||||||
|
class E2eWrongPassphraseError implements Exception {
|
||||||
|
@override
|
||||||
|
String toString() => 'E2eWrongPassphraseError: wrong sync passphrase';
|
||||||
|
}
|
||||||
@ -145,6 +145,25 @@ void main() {
|
|||||||
throwsA(isA<E2eDecryptError>()),
|
throwsA(isA<E2eDecryptError>()),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
test('unknown envelope version asks for an app update', () async {
|
||||||
|
expect(
|
||||||
|
() => openLogText('{"v":99,"r":{}}', _cipher(), path: _path),
|
||||||
|
throwsA(
|
||||||
|
isA<E2eDecryptError>().having(
|
||||||
|
(e) => e.toString(),
|
||||||
|
'message',
|
||||||
|
contains('format 99'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
test('mis-shaped record', () async {
|
||||||
|
expect(
|
||||||
|
() =>
|
||||||
|
openLogText('{"v":1,"r":{"n1":{"p":"x"}}}', _cipher(), path: _path),
|
||||||
|
throwsA(isA<E2eDecryptError>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
test('text that is not a log is sealed whole and opens back', () async {
|
test('text that is not a log is sealed whole and opens back', () async {
|
||||||
|
|||||||
55
crdt_sync_dart/test/e2e_migration_blobs_test.dart
Normal file
55
crdt_sync_dart/test/e2e_migration_blobs_test.dart
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
/// Migration over flat `<node>.json` leaves and non-log source blobs.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:test/test.dart';
|
||||||
|
|
||||||
|
import 'e2e_fakes.dart';
|
||||||
|
|
||||||
|
const _old = 'app/notes';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
final layout = E2eLayout.of(_old);
|
||||||
|
|
||||||
|
Future<E2eKey> key(RemoteStore remote) => unlockE2e(
|
||||||
|
store: remote,
|
||||||
|
pathPrefix: layout.prefix,
|
||||||
|
passphrase: 'pw',
|
||||||
|
params: cheapArgon,
|
||||||
|
e2ePath: layout.e2ePath,
|
||||||
|
);
|
||||||
|
|
||||||
|
test('a flat leaf is read one by one when the backend has no bulk', () async {
|
||||||
|
final inner = MemoryRemote({
|
||||||
|
'$_old/node.json': encodeLog(logOf({'a': 'milk'})),
|
||||||
|
});
|
||||||
|
final remote = PlainRemote(inner);
|
||||||
|
final report = await copyToEncrypted(
|
||||||
|
store: remote,
|
||||||
|
key: await key(remote),
|
||||||
|
fromPrefix: _old,
|
||||||
|
layout: layout,
|
||||||
|
);
|
||||||
|
expect(report.copied, 1);
|
||||||
|
final blob = inner.files['${layout.prefix}/node.json']!;
|
||||||
|
expect(blob, isNot(contains('milk')));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a source blob that is not a JSON object is skipped', () async {
|
||||||
|
final remote = MemoryRemote({
|
||||||
|
'$_old/list/log.json': '[1,2]',
|
||||||
|
'$_old/shape/log.json': '{"a":5}',
|
||||||
|
});
|
||||||
|
final report = await copyToEncrypted(
|
||||||
|
store: remote,
|
||||||
|
key: await key(remote),
|
||||||
|
fromPrefix: _old,
|
||||||
|
layout: layout,
|
||||||
|
);
|
||||||
|
expect(report.copied, 0);
|
||||||
|
expect(
|
||||||
|
report.skipped,
|
||||||
|
unorderedEquals(['list/log.json', 'shape/log.json']),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -95,4 +95,18 @@ void main() {
|
|||||||
final map = await state.store.getStringMap('app/notes-e2e');
|
final map = await state.store.getStringMap('app/notes-e2e');
|
||||||
expect(map['k1'], log);
|
expect(map['k1'], log);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('a cache that reports a bad header locks as badHeader', () async {
|
||||||
|
final state = await openEncryptedStore(
|
||||||
|
store: MemoryRemote(),
|
||||||
|
oldPrefix: _old,
|
||||||
|
readPassphrase: () async => 'pw',
|
||||||
|
params: cheapArgon,
|
||||||
|
keyCache: E2eKeyCache(
|
||||||
|
read: () async => throw E2eHeaderError('bad header'),
|
||||||
|
write: (_) async {},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect((state as E2eLocked).reason, E2eLockReason.badHeader);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@ -13,6 +13,9 @@ Future<E2eState> _open(MemoryRemote r, String? pass) => openEncryptedStore(
|
|||||||
);
|
);
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
|
// The copy memo is process-wide; a prior open would skip the copy.
|
||||||
|
setUp(resetE2eCopyMemo);
|
||||||
|
|
||||||
test('no passphrase is locked', () async {
|
test('no passphrase is locked', () async {
|
||||||
for (final p in [null, '']) {
|
for (final p in [null, '']) {
|
||||||
final s = await _open(MemoryRemote(), p);
|
final s = await _open(MemoryRemote(), p);
|
||||||
|
|||||||
53
crdt_sync_dart/test/encrypting_store_bulk_test.dart
Normal file
53
crdt_sync_dart/test/encrypting_store_bulk_test.dart
Normal file
@ -0,0 +1,53 @@
|
|||||||
|
/// EncryptingStore.getStringMap on a data dir that also holds non-log
|
||||||
|
/// entries and unreadable ones.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:test/test.dart';
|
||||||
|
|
||||||
|
import 'e2e_fakes.dart';
|
||||||
|
|
||||||
|
const _old = 'settings-sync';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
final layout = E2eLayout.of(_old);
|
||||||
|
|
||||||
|
Future<E2eKey> key(RemoteStore remote) => unlockE2e(
|
||||||
|
store: remote,
|
||||||
|
pathPrefix: layout.prefix,
|
||||||
|
passphrase: 'pw',
|
||||||
|
params: cheapArgon,
|
||||||
|
e2ePath: layout.e2ePath,
|
||||||
|
);
|
||||||
|
|
||||||
|
EncryptingStore open(
|
||||||
|
MemoryRemote remote,
|
||||||
|
E2eKey k, {
|
||||||
|
bool acceptPlaintext = true,
|
||||||
|
}) => EncryptingStore(
|
||||||
|
remote,
|
||||||
|
k,
|
||||||
|
pathPrefix: layout.prefix,
|
||||||
|
revsPath: layout.revsPath,
|
||||||
|
e2ePath: layout.e2ePath,
|
||||||
|
acceptPlaintext: acceptPlaintext,
|
||||||
|
);
|
||||||
|
|
||||||
|
test('the header inside the prefix passes through undecrypted', () async {
|
||||||
|
final remote = MemoryRemote();
|
||||||
|
final store = open(remote, await key(remote));
|
||||||
|
final log = encodeLog(logOf({'a': 'secret'}));
|
||||||
|
await store.putFileText('${layout.prefix}/node.json', log, message: 'm');
|
||||||
|
final map = await store.getStringMap(layout.prefix);
|
||||||
|
expect(map['e2e'], remote.files[layout.e2ePath]);
|
||||||
|
expect(map['node.json'], log);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an unreadable entry is dropped from the bulk read', () async {
|
||||||
|
final remote = MemoryRemote();
|
||||||
|
final store = open(remote, await key(remote), acceptPlaintext: false);
|
||||||
|
remote.files['${layout.prefix}/old.json'] = encodeLog(logOf({'a': 'x'}));
|
||||||
|
final map = await store.getStringMap(layout.prefix);
|
||||||
|
expect(map.containsKey('old.json'), isFalse);
|
||||||
|
});
|
||||||
|
}
|
||||||
72
crdt_sync_dart/test/encrypting_store_delegation_test.dart
Normal file
72
crdt_sync_dart/test/encrypting_store_delegation_test.dart
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
/// EncryptingStore forwards what it does not seal to the inner store.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:glados/glados.dart' show Random;
|
||||||
|
import 'package:test/test.dart';
|
||||||
|
|
||||||
|
import 'e2e_fakes.dart';
|
||||||
|
|
||||||
|
const _prefix = 'todo-sync/notes';
|
||||||
|
const _revs = 'todo-sync/revs';
|
||||||
|
|
||||||
|
Future<E2eKey> _key(MemoryRemote remote, [String passphrase = 'pw']) =>
|
||||||
|
unlockE2e(
|
||||||
|
store: remote,
|
||||||
|
pathPrefix: _prefix,
|
||||||
|
passphrase: passphrase,
|
||||||
|
params: cheapArgon,
|
||||||
|
random: Random(1),
|
||||||
|
);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('paths outside the prefix pass through untouched', () async {
|
||||||
|
final remote = MemoryRemote();
|
||||||
|
final store = EncryptingStore(
|
||||||
|
remote,
|
||||||
|
await _key(remote),
|
||||||
|
pathPrefix: _prefix,
|
||||||
|
);
|
||||||
|
await store.putFileText('other/x', '{"a":1}', message: 'm');
|
||||||
|
expect(remote.files['other/x'], '{"a":1}');
|
||||||
|
expect(await store.getFileText('other/x'), '{"a":1}');
|
||||||
|
expect(await store.getFileText('$_prefix/none/log.json'), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
group('delegation', () {
|
||||||
|
test('bulk reads forward when the inner store has them', () async {
|
||||||
|
final remote = MemoryRemote({'$_revs/a': 'r'});
|
||||||
|
final store = EncryptingStore(
|
||||||
|
remote,
|
||||||
|
await _key(remote),
|
||||||
|
pathPrefix: _prefix,
|
||||||
|
);
|
||||||
|
expect(await store.getStringMap(_revs), {'a': 'r'});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bulk reads degrade to "fetch everything" without them', () async {
|
||||||
|
final remote = MemoryRemote({'$_revs/a': 'r'});
|
||||||
|
final store = EncryptingStore(
|
||||||
|
PlainRemote(remote),
|
||||||
|
await _key(remote),
|
||||||
|
pathPrefix: _prefix,
|
||||||
|
);
|
||||||
|
expect(await store.getStringMap(_revs), isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('list, delete, access and close reach the inner store', () async {
|
||||||
|
final remote = MemoryRemote({'$_prefix/a/log.json': '{}'});
|
||||||
|
final store = EncryptingStore(
|
||||||
|
remote,
|
||||||
|
await _key(remote),
|
||||||
|
pathPrefix: _prefix,
|
||||||
|
);
|
||||||
|
expect(await store.listDirectory(_prefix), ['a']);
|
||||||
|
await store.deleteFile('$_prefix/a/log.json', message: 'm');
|
||||||
|
expect(remote.files.containsKey('$_prefix/a/log.json'), isFalse);
|
||||||
|
expect(await store.canAccessRemote(), isTrue);
|
||||||
|
store.close();
|
||||||
|
expect(remote.closed, isTrue);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -150,19 +150,6 @@ void main() {
|
|||||||
expect(remote.files['wake-alarm/e2e'], contains('argon2id'));
|
expect(remote.files['wake-alarm/e2e'], contains('argon2id'));
|
||||||
});
|
});
|
||||||
|
|
||||||
test('paths outside the prefix pass through untouched', () async {
|
|
||||||
final remote = MemoryRemote();
|
|
||||||
final store = EncryptingStore(
|
|
||||||
remote,
|
|
||||||
await _key(remote),
|
|
||||||
pathPrefix: _prefix,
|
|
||||||
);
|
|
||||||
await store.putFileText('other/x', '{"a":1}', message: 'm');
|
|
||||||
expect(remote.files['other/x'], '{"a":1}');
|
|
||||||
expect(await store.getFileText('other/x'), '{"a":1}');
|
|
||||||
expect(await store.getFileText('$_prefix/none/log.json'), isNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('a flat <prefix>/<node>.json layout (todo) is sealed too', () async {
|
test('a flat <prefix>/<node>.json layout (todo) is sealed too', () async {
|
||||||
final remote = MemoryRemote();
|
final remote = MemoryRemote();
|
||||||
final store = EncryptingStore(
|
final store = EncryptingStore(
|
||||||
@ -205,43 +192,6 @@ void main() {
|
|||||||
expect(await _tick(store, 'phone', {}), isEmpty);
|
expect(await _tick(store, 'phone', {}), isEmpty);
|
||||||
});
|
});
|
||||||
|
|
||||||
group('delegation', () {
|
|
||||||
test('bulk reads forward when the inner store has them', () async {
|
|
||||||
final remote = MemoryRemote({'$_revs/a': 'r'});
|
|
||||||
final store = EncryptingStore(
|
|
||||||
remote,
|
|
||||||
await _key(remote),
|
|
||||||
pathPrefix: _prefix,
|
|
||||||
);
|
|
||||||
expect(await store.getStringMap(_revs), {'a': 'r'});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('bulk reads degrade to "fetch everything" without them', () async {
|
|
||||||
final remote = MemoryRemote({'$_revs/a': 'r'});
|
|
||||||
final store = EncryptingStore(
|
|
||||||
PlainRemote(remote),
|
|
||||||
await _key(remote),
|
|
||||||
pathPrefix: _prefix,
|
|
||||||
);
|
|
||||||
expect(await store.getStringMap(_revs), isEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('list, delete, access and close reach the inner store', () async {
|
|
||||||
final remote = MemoryRemote({'$_prefix/a/log.json': '{}'});
|
|
||||||
final store = EncryptingStore(
|
|
||||||
remote,
|
|
||||||
await _key(remote),
|
|
||||||
pathPrefix: _prefix,
|
|
||||||
);
|
|
||||||
expect(await store.listDirectory(_prefix), ['a']);
|
|
||||||
await store.deleteFile('$_prefix/a/log.json', message: 'm');
|
|
||||||
expect(remote.files.containsKey('$_prefix/a/log.json'), isFalse);
|
|
||||||
expect(await store.canAccessRemote(), isTrue);
|
|
||||||
store.close();
|
|
||||||
expect(remote.closed, isTrue);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// Differential: the same sync rounds over a plain and an encrypting relay
|
// Differential: the same sync rounds over a plain and an encrypting relay
|
||||||
// must converge to the same logs.
|
// must converge to the same logs.
|
||||||
Glados(
|
Glados(
|
||||||
|
|||||||
@ -103,13 +103,15 @@ repos:
|
|||||||
- --disable-error-code=list-item
|
- --disable-error-code=list-item
|
||||||
|
|
||||||
- repo: https://github.com/pylint-dev/pylint
|
- repo: https://github.com/pylint-dev/pylint
|
||||||
rev: v4.0.8
|
rev: v4.1.4
|
||||||
hooks:
|
hooks:
|
||||||
- id: pylint
|
- id: pylint
|
||||||
args:
|
args:
|
||||||
- --rcfile=earned_time/pyproject.toml
|
- --rcfile=earned_time/pyproject.toml
|
||||||
- --fail-under=10
|
- --fail-under=10
|
||||||
- --jobs=4
|
# One process: with --jobs>1 pylint pickles its AST via dill, which
|
||||||
|
# dies on Python 3.15 (code objects lost co_lnotab), 2026-11-16.
|
||||||
|
- --jobs=1
|
||||||
additional_dependencies:
|
additional_dependencies:
|
||||||
- pytest
|
- pytest
|
||||||
|
|
||||||
@ -143,3 +145,5 @@ repos:
|
|||||||
- id: codespell
|
- id: codespell
|
||||||
args:
|
args:
|
||||||
- --skip=*.json,*.lock,.git,__pycache__,.venv
|
- --skip=*.json,*.lock,.git,__pycache__,.venv
|
||||||
|
# `checkin` is a timer event name on the wire, not a typo.
|
||||||
|
- --ignore-words-list=checkin
|
||||||
|
|||||||
34
earned_time/DOCS-maturity.md
Normal file
34
earned_time/DOCS-maturity.md
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
# earned_time: gate maturity (0.6.0)
|
||||||
|
|
||||||
|
How far to trust a gate is computed from its ledger, never listed by name:
|
||||||
|
`maturity(earner, ledger, key_file, today) -> Maturity` (`_maturity.py`).
|
||||||
|
|
||||||
|
- **Real credit:** HMAC-verified `credit` row, accepted by the earner's
|
||||||
|
`match`, not manual (`detail.source` `manual`/`manual_grant`, `entry_id`
|
||||||
|
`manual:`/`manual_grant:`), and `amount > 0` when the row has one -- a
|
||||||
|
gate's own re-evaluation grant (`detail.grant_of`, book-guard `bonus:`
|
||||||
|
rows) may pay 0. A matcher cannot loosen this (`anki_match` alone accepts a
|
||||||
|
`manual_grant` row).
|
||||||
|
- **Levels:** `new` = no real credit, or no `Earner.confirmed_on` (set by
|
||||||
|
kuhy); `mature` = at least `MATURE_MIN_CREDIT_DAYS` (14) distinct credit
|
||||||
|
days and the first at least `MATURE_MIN_AGE_DAYS` (21) old; else `maturing`.
|
||||||
|
An unreadable ledger or key is `checked=False`, `new`, reason recorded.
|
||||||
|
- **Penalty start:** `penalty_start(earner, first_credit)` =
|
||||||
|
max(`penalty_from`, day after the first real credit, day after
|
||||||
|
`confirmed_on`). No first credit (never paid out, or could not check) is
|
||||||
|
not penalised -- unless `confirmed_on` is set: then fail closed,
|
||||||
|
max(`penalty_from`, day after `confirmed_on`), so deleting or locking a
|
||||||
|
ledger cannot lift a penalty. Pass `first_credits={name: Maturity.first_credit}`, computed
|
||||||
|
over `earners_for(day)` (until 0.9.0 two earners shared the name `automation`), to `resolve`
|
||||||
|
/ `base_for` to apply it; omitted, a penalty starts at `penalty_from`, as
|
||||||
|
in 0.5.0. It can only delay a penalty, never add one.
|
||||||
|
- **Ladder floor (0.6.1):** the same start gates the shutdown floor. A rung
|
||||||
|
comes off the floor only for a pure bonus (no `penalty_from`: workout,
|
||||||
|
LeetCode) or an earner whose penalty has started, so a gate that never paid
|
||||||
|
out cannot lower it either (10-10, tutor never credited: 19:50, not 19:00).
|
||||||
|
An unwired consumer (no `first_credits`) cuts the tutor from `penalty_from`:
|
||||||
|
19:00 / 3 h.
|
||||||
|
- **CLI:** `python -m earned_time maturity [--json] [--day YYYY-MM-DD]`
|
||||||
|
prints one row per ledger-backed earner of every registry. It and
|
||||||
|
`leisure_from()` alone resolve real paths (`~/<Earner.ledger>`,
|
||||||
|
`/etc/workout-locker/hmac.key`), and it only reads.
|
||||||
@ -124,38 +124,8 @@ it, and ignore answers for an earner of another day's registry.
|
|||||||
|
|
||||||
## Gate maturity (0.6.0)
|
## Gate maturity (0.6.0)
|
||||||
|
|
||||||
How far to trust a gate is computed from its ledger, never listed by name:
|
How far to trust a gate, computed from its ledger by `maturity()`, is in
|
||||||
`maturity(earner, ledger, key_file, today) -> Maturity` (`_maturity.py`).
|
[DOCS-maturity.md](DOCS-maturity.md).
|
||||||
|
|
||||||
- **Real credit:** HMAC-verified `credit` row, accepted by the earner's
|
|
||||||
`match`, not manual (`detail.source` `manual`/`manual_grant`, `entry_id`
|
|
||||||
`manual:`/`manual_grant:`), and `amount > 0` when the row has one -- a
|
|
||||||
gate's own re-evaluation grant (`detail.grant_of`, book-guard `bonus:`
|
|
||||||
rows) may pay 0. A matcher cannot loosen this (`anki_match` alone accepts a
|
|
||||||
`manual_grant` row).
|
|
||||||
- **Levels:** `new` = no real credit, or no `Earner.confirmed_on` (set by
|
|
||||||
kuhy); `mature` = at least `MATURE_MIN_CREDIT_DAYS` (14) distinct credit
|
|
||||||
days and the first at least `MATURE_MIN_AGE_DAYS` (21) old; else `maturing`.
|
|
||||||
An unreadable ledger or key is `checked=False`, `new`, reason recorded.
|
|
||||||
- **Penalty start:** `penalty_start(earner, first_credit)` =
|
|
||||||
max(`penalty_from`, day after the first real credit, day after
|
|
||||||
`confirmed_on`). No first credit (never paid out, or could not check) is
|
|
||||||
not penalised -- unless `confirmed_on` is set: then fail closed,
|
|
||||||
max(`penalty_from`, day after `confirmed_on`), so deleting or locking a
|
|
||||||
ledger cannot lift a penalty. Pass `first_credits={name: Maturity.first_credit}`, computed
|
|
||||||
over `earners_for(day)` (until 0.9.0 two earners shared the name `automation`), to `resolve`
|
|
||||||
/ `base_for` to apply it; omitted, a penalty starts at `penalty_from`, as
|
|
||||||
in 0.5.0. It can only delay a penalty, never add one.
|
|
||||||
- **Ladder floor (0.6.1):** the same start gates the shutdown floor. A rung
|
|
||||||
comes off the floor only for a pure bonus (no `penalty_from`: workout,
|
|
||||||
LeetCode) or an earner whose penalty has started, so a gate that never paid
|
|
||||||
out cannot lower it either (10-10, tutor never credited: 19:50, not 19:00).
|
|
||||||
An unwired consumer (no `first_credits`) cuts the tutor from `penalty_from`:
|
|
||||||
19:00 / 3 h.
|
|
||||||
- **CLI:** `python -m earned_time maturity [--json] [--day YYYY-MM-DD]`
|
|
||||||
prints one row per ledger-backed earner of every registry. It and
|
|
||||||
`leisure_from()` alone resolve real paths (`~/<Earner.ledger>`,
|
|
||||||
`/etc/workout-locker/hmac.key`), and it only reads.
|
|
||||||
|
|
||||||
## API
|
## API
|
||||||
|
|
||||||
|
|||||||
@ -7,12 +7,15 @@ from dataclasses import dataclass
|
|||||||
from datetime import date, timedelta
|
from datetime import date, timedelta
|
||||||
import importlib
|
import importlib
|
||||||
import logging
|
import logging
|
||||||
from typing import Any, Final
|
from typing import TYPE_CHECKING, Final, Protocol
|
||||||
|
|
||||||
from earned_time._ladder import shutdown_units_minutes
|
from earned_time._ladder import shutdown_units_minutes
|
||||||
from earned_time._match import focus_match
|
from earned_time._match import focus_match
|
||||||
from earned_time._policy import Earner
|
from earned_time._policy import Earner
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Iterable
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"FOCUS_LEDGER",
|
"FOCUS_LEDGER",
|
||||||
"FOCUS_WATCH",
|
"FOCUS_WATCH",
|
||||||
@ -27,6 +30,16 @@ _logger: Final = logging.getLogger(__name__)
|
|||||||
_warned: set[str] = set()
|
_warned: set[str] = set()
|
||||||
|
|
||||||
|
|
||||||
|
class _Project(Protocol):
|
||||||
|
"""What this module reads off a ``focus_project.Project``."""
|
||||||
|
|
||||||
|
start: date
|
||||||
|
daily_minutes: int
|
||||||
|
|
||||||
|
#: The gate names the project stands in for.
|
||||||
|
replaces: Iterable[str]
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class FocusEarner(Earner):
|
class FocusEarner(Earner):
|
||||||
"""Counted; ``gaming_minutes``/``shutdown_minutes`` pay a FULL day.
|
"""Counted; ``gaming_minutes``/``shutdown_minutes`` pay a FULL day.
|
||||||
@ -45,31 +58,34 @@ class FocusEarner(Earner):
|
|||||||
def shutdown_for(
|
def shutdown_for(
|
||||||
self,
|
self,
|
||||||
units: int,
|
units: int,
|
||||||
day: date | None = None, # noqa: ARG002
|
day: date | None = None,
|
||||||
) -> int:
|
) -> int:
|
||||||
"""Shutdown minutes of ``units`` focused minutes, floored."""
|
"""Shutdown minutes of ``units`` focused minutes, floored."""
|
||||||
|
del day # the base signature takes it; focus pay is the same every day
|
||||||
return self.capped(units) * self.shutdown_minutes // (self.max_units or 1)
|
return self.capped(units) * self.shutdown_minutes // (self.max_units or 1)
|
||||||
|
|
||||||
|
|
||||||
def _active(day: date) -> Any: # noqa: ANN401
|
def _active(day: date) -> _Project | None:
|
||||||
"""The active project on ``day``; ``None`` for none or on any failure."""
|
"""The active project on ``day``; ``None`` for none or on any failure."""
|
||||||
try:
|
try:
|
||||||
return importlib.import_module("focus_project").active(day)
|
return importlib.import_module("focus_project").active(day)
|
||||||
except Exception as exc: # noqa: BLE001 # pylint: disable=broad-exception-caught
|
except Exception as exc: # pylint: disable=broad-exception-caught
|
||||||
message = f"focus_project unusable ({type(exc).__name__}: {exc})"
|
message = f"focus_project unusable ({type(exc).__name__}: {exc})"
|
||||||
if message not in _warned:
|
if message not in _warned:
|
||||||
_warned.add(message)
|
_warned.add(message)
|
||||||
_logger.warning("%s; behaving as if no project is active", message)
|
_logger.warning(
|
||||||
|
"%s; behaving as if no project is active", message, exc_info=True
|
||||||
|
)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def daily_on(project: Any, day: date) -> int: # noqa: ANN401
|
def daily_on(project: _Project, day: date) -> int:
|
||||||
"""``day``'s target: ``project.daily_on(day)`` (a later edit never re-prices it)."""
|
"""``day``'s target: ``project.daily_on(day)`` (a later edit never re-prices it)."""
|
||||||
pick = getattr(project, "daily_on", None)
|
pick = getattr(project, "daily_on", None)
|
||||||
return int(pick(day) if pick is not None else project.daily_minutes)
|
return int(pick(day) if pick is not None else project.daily_minutes)
|
||||||
|
|
||||||
|
|
||||||
def focus_earner(project: Any, dropped: tuple[Earner, ...], day: date) -> Earner: # noqa: ANN401
|
def focus_earner(project: _Project, dropped: tuple[Earner, ...], day: date) -> Earner:
|
||||||
"""The ``focus`` earner paying what ``dropped`` paid, over ``project``.
|
"""The ``focus`` earner paying what ``dropped`` paid, over ``project``.
|
||||||
|
|
||||||
Gaming: the cut is every dropped gate's full pay; a full day pays that plus
|
Gaming: the cut is every dropped gate's full pay; a full day pays that plus
|
||||||
|
|||||||
@ -2,9 +2,9 @@
|
|||||||
# floor is satisfied by anything newer, so it tells a checker nothing
|
# floor is satisfied by anything newer, so it tells a checker nothing
|
||||||
# about whether this repo is actually current.
|
# about whether this repo is actually current.
|
||||||
bandit[toml]==1.9.4
|
bandit[toml]==1.9.4
|
||||||
mypy==2.4.0
|
mypy==2.4.1
|
||||||
pre-commit==4.7.0
|
pre-commit==4.7.0
|
||||||
pylint==4.1.3
|
pylint==4.1.4
|
||||||
pytest==9.1.1
|
pytest==9.2.0
|
||||||
pytest-cov==7.1.0
|
pytest-cov==7.1.0
|
||||||
ruff==0.17.2
|
ruff==0.17.5
|
||||||
|
|||||||
@ -101,13 +101,15 @@ repos:
|
|||||||
- --disable-error-code=list-item
|
- --disable-error-code=list-item
|
||||||
|
|
||||||
- repo: https://github.com/pylint-dev/pylint
|
- repo: https://github.com/pylint-dev/pylint
|
||||||
rev: v4.0.8
|
rev: v4.1.4
|
||||||
hooks:
|
hooks:
|
||||||
- id: pylint
|
- id: pylint
|
||||||
args:
|
args:
|
||||||
- --rcfile=feedback_inbox/pyproject.toml
|
- --rcfile=feedback_inbox/pyproject.toml
|
||||||
- --fail-under=10
|
- --fail-under=10
|
||||||
- --jobs=4
|
# One process: with --jobs>1 pylint pickles its AST via dill, which
|
||||||
|
# dies on Python 3.15 (code objects lost co_lnotab), 2026-11-16.
|
||||||
|
- --jobs=1
|
||||||
additional_dependencies:
|
additional_dependencies:
|
||||||
- pytest
|
- pytest
|
||||||
|
|
||||||
|
|||||||
@ -4,7 +4,7 @@
|
|||||||
bandit[toml]==1.9.4
|
bandit[toml]==1.9.4
|
||||||
mypy==2.4.1
|
mypy==2.4.1
|
||||||
pre-commit==4.7.0
|
pre-commit==4.7.0
|
||||||
pylint==4.1.3
|
pylint==4.1.4
|
||||||
pytest==9.2.0
|
pytest==9.2.0
|
||||||
pytest-cov==7.1.0
|
pytest-cov==7.1.0
|
||||||
ruff==0.17.4
|
ruff==0.17.5
|
||||||
|
|||||||
@ -33,6 +33,8 @@ repos:
|
|||||||
- id: debug-statements
|
- id: debug-statements
|
||||||
- id: name-tests-test
|
- id: name-tests-test
|
||||||
args: [--pytest-test-first]
|
args: [--pytest-test-first]
|
||||||
|
# Shared test helpers (rows, fixtures) are _private modules, not tests.
|
||||||
|
exclude: ^focus_project/focus_project/tests/_[a-z_]+\.py$
|
||||||
- id: check-ast
|
- id: check-ast
|
||||||
- id: mixed-line-ending
|
- id: mixed-line-ending
|
||||||
args: [--fix=lf]
|
args: [--fix=lf]
|
||||||
@ -101,18 +103,21 @@ repos:
|
|||||||
- --disable-error-code=list-item
|
- --disable-error-code=list-item
|
||||||
|
|
||||||
- repo: https://github.com/pylint-dev/pylint
|
- repo: https://github.com/pylint-dev/pylint
|
||||||
rev: v4.0.8
|
rev: v4.1.4
|
||||||
hooks:
|
hooks:
|
||||||
- id: pylint
|
- id: pylint
|
||||||
args:
|
args:
|
||||||
- --rcfile=focus_project/pyproject.toml
|
- --rcfile=focus_project/pyproject.toml
|
||||||
- --fail-under=10
|
- --fail-under=10
|
||||||
- --jobs=4
|
# One process: with --jobs>1 pylint pickles its AST via dill, which
|
||||||
|
# dies on Python 3.15 (code objects lost co_lnotab), 2026-11-16.
|
||||||
|
- --jobs=1
|
||||||
additional_dependencies:
|
additional_dependencies:
|
||||||
- pytest
|
- pytest
|
||||||
# Kept in step with pyproject.toml, so pylint resolves the crdt_sync
|
# Kept in step with pyproject.toml, so pylint resolves the crdt_sync
|
||||||
# imports instead of scoring every one of them as import-error.
|
# imports instead of scoring every one of them as import-error.
|
||||||
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
|
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
|
||||||
|
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.21.0#subdirectory=earned_time
|
||||||
|
|
||||||
- repo: https://github.com/PyCQA/bandit
|
- repo: https://github.com/PyCQA/bandit
|
||||||
rev: 1.9.4
|
rev: 1.9.4
|
||||||
@ -144,3 +149,5 @@ repos:
|
|||||||
- id: codespell
|
- id: codespell
|
||||||
args:
|
args:
|
||||||
- --skip=*.json,*.lock,.git,__pycache__,.venv
|
- --skip=*.json,*.lock,.git,__pycache__,.venv
|
||||||
|
# `checkin` is a timer event name on the wire, not a typo.
|
||||||
|
- --ignore-words-list=checkin
|
||||||
|
|||||||
@ -93,7 +93,7 @@ def _validate(project: Project) -> None:
|
|||||||
raise ValueError(msg)
|
raise ValueError(msg)
|
||||||
|
|
||||||
|
|
||||||
def create_project( # noqa: PLR0913
|
def create_project( # pylint: disable=too-many-arguments,too-many-locals
|
||||||
project_id: str,
|
project_id: str,
|
||||||
*,
|
*,
|
||||||
name: str,
|
name: str,
|
||||||
@ -161,9 +161,8 @@ def end_project(project_id: str, day: date) -> Project:
|
|||||||
"""
|
"""
|
||||||
with _store.locked():
|
with _store.locked():
|
||||||
existing = _store.read_all()
|
existing = _store.read_all()
|
||||||
for i, project in enumerate(existing):
|
i = _store.index_of(existing, project_id)
|
||||||
if project.id != project_id:
|
project = existing[i]
|
||||||
continue
|
|
||||||
if project.ended_on is not None:
|
if project.ended_on is not None:
|
||||||
msg = f"project {project_id!r} already ended on {project.ended_on}"
|
msg = f"project {project_id!r} already ended on {project.ended_on}"
|
||||||
raise ValueError(msg)
|
raise ValueError(msg)
|
||||||
@ -177,4 +176,3 @@ def end_project(project_id: str, day: date) -> Project:
|
|||||||
existing[i] = ended
|
existing[i] = ended
|
||||||
_store.write_all(existing)
|
_store.write_all(existing)
|
||||||
return ended
|
return ended
|
||||||
raise KeyError(project_id)
|
|
||||||
|
|||||||
@ -3,8 +3,12 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import date
|
from datetime import UTC, datetime
|
||||||
import time
|
import time
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
|
||||||
def now() -> float:
|
def now() -> float:
|
||||||
@ -14,4 +18,4 @@ def now() -> float:
|
|||||||
|
|
||||||
def today() -> date:
|
def today() -> date:
|
||||||
"""The local calendar date right now."""
|
"""The local calendar date right now."""
|
||||||
return date.fromtimestamp(now()) # noqa: DTZ012 (local day by contract)
|
return datetime.fromtimestamp(now(), tz=UTC).astimezone().date()
|
||||||
|
|||||||
@ -5,12 +5,15 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
from typing import Any
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
from focus_project._errors import RegistryError
|
from focus_project._errors import RegistryError
|
||||||
from focus_project._kind import FOCUS, INTERVIEW, interview_minutes
|
from focus_project._kind import FOCUS, INTERVIEW, interview_minutes
|
||||||
from focus_project._trips import Trip
|
from focus_project._trips import Trip
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Mapping
|
||||||
|
|
||||||
GATES = frozenset({"leetcode", "reading", "tutor"})
|
GATES = frozenset({"leetcode", "reading", "tutor"})
|
||||||
_ALIASES = {"book": "reading"}
|
_ALIASES = {"book": "reading"}
|
||||||
|
|
||||||
@ -53,7 +56,7 @@ class Limits:
|
|||||||
return row
|
return row
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_dict(cls, row: Any) -> Limits: # noqa: ANN401
|
def from_dict(cls, row: Mapping[str, Any]) -> Limits:
|
||||||
"""Parse a history row (errors surface as RegistryError upstream)."""
|
"""Parse a history row (errors surface as RegistryError upstream)."""
|
||||||
gates = row.get("replaces")
|
gates = row.get("replaces")
|
||||||
return cls(
|
return cls(
|
||||||
@ -65,7 +68,7 @@ class Limits:
|
|||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class Project:
|
class Project: # pylint: disable=too-many-instance-attributes
|
||||||
"""One time-boxed focus project; at most one is active per day."""
|
"""One time-boxed focus project; at most one is active per day."""
|
||||||
|
|
||||||
id: str
|
id: str
|
||||||
@ -154,7 +157,7 @@ class Project:
|
|||||||
return row
|
return row
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_dict(cls, row: Any) -> Project: # noqa: ANN401
|
def from_dict(cls, row: Mapping[str, Any]) -> Project:
|
||||||
"""Parse a registry row, or raise :class:`RegistryError`."""
|
"""Parse a registry row, or raise :class:`RegistryError`."""
|
||||||
try:
|
try:
|
||||||
ended = row.get("ended_on")
|
ended = row.get("ended_on")
|
||||||
|
|||||||
@ -144,7 +144,7 @@ def _clean(
|
|||||||
return True # tap, slot_confirm
|
return True # tap, slot_confirm
|
||||||
|
|
||||||
|
|
||||||
def record_evidence( # noqa: PLR0913
|
def record_evidence( # pylint: disable=too-many-arguments
|
||||||
project_id: str,
|
project_id: str,
|
||||||
milestone: str,
|
milestone: str,
|
||||||
kind: str,
|
kind: str,
|
||||||
|
|||||||
@ -28,6 +28,15 @@ def locked() -> Iterator[None]:
|
|||||||
yield
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
def _project_rows(text: str) -> list[object]:
|
||||||
|
"""The ``projects`` list of a registry file; ValueError/KeyError/TypeError."""
|
||||||
|
rows = json.loads(text)["projects"]
|
||||||
|
if not isinstance(rows, list):
|
||||||
|
msg = "'projects' is not a list"
|
||||||
|
raise TypeError(msg)
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
def read_all() -> list[Project]:
|
def read_all() -> list[Project]:
|
||||||
"""Every project; a missing file is empty, a bad one raises."""
|
"""Every project; a missing file is empty, a bad one raises."""
|
||||||
try:
|
try:
|
||||||
@ -35,16 +44,21 @@ def read_all() -> list[Project]:
|
|||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
return []
|
return []
|
||||||
try:
|
try:
|
||||||
rows = json.loads(text)["projects"]
|
rows = _project_rows(text)
|
||||||
if not isinstance(rows, list):
|
|
||||||
msg = "'projects' is not a list"
|
|
||||||
raise TypeError(msg) # noqa: TRY301
|
|
||||||
except (ValueError, KeyError, TypeError) as exc:
|
except (ValueError, KeyError, TypeError) as exc:
|
||||||
msg = f"unreadable {projects_path()}: {exc}"
|
msg = f"unreadable {projects_path()}: {exc}"
|
||||||
raise RegistryError(msg) from exc
|
raise RegistryError(msg) from exc
|
||||||
return [Project.from_dict(row) for row in rows]
|
return [Project.from_dict(row) for row in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def index_of(projects: list[Project], project_id: str) -> int:
|
||||||
|
"""Position of the first project with ``project_id``; KeyError if none."""
|
||||||
|
for i, project in enumerate(projects):
|
||||||
|
if project.id == project_id:
|
||||||
|
return i
|
||||||
|
raise KeyError(project_id)
|
||||||
|
|
||||||
|
|
||||||
def write_all(projects: list[Project]) -> None:
|
def write_all(projects: list[Project]) -> None:
|
||||||
"""Replace the file atomically: temp file in the same dir, fsync, rename."""
|
"""Replace the file atomically: temp file in the same dir, fsync, rename."""
|
||||||
target = projects_path()
|
target = projects_path()
|
||||||
@ -55,7 +69,7 @@ def write_all(projects: list[Project]) -> None:
|
|||||||
handle.write(payload + "\n")
|
handle.write(payload + "\n")
|
||||||
handle.flush()
|
handle.flush()
|
||||||
os.fsync(handle.fileno())
|
os.fsync(handle.fileno())
|
||||||
os.replace(tmp, target) # noqa: PTH105
|
Path(tmp).replace(target)
|
||||||
except BaseException:
|
except BaseException:
|
||||||
Path(tmp).unlink(missing_ok=True)
|
Path(tmp).unlink(missing_ok=True)
|
||||||
raise
|
raise
|
||||||
|
|||||||
@ -4,7 +4,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import dataclass, replace
|
from dataclasses import dataclass, replace
|
||||||
from datetime import date, timedelta
|
from datetime import UTC, date, datetime, timedelta
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from focus_project import _store
|
from focus_project import _store
|
||||||
@ -113,7 +113,7 @@ def apply_update(
|
|||||||
project_id: str,
|
project_id: str,
|
||||||
*,
|
*,
|
||||||
today: date | None = None,
|
today: date | None = None,
|
||||||
**changes: Any, # noqa: ANN401
|
**changes: object,
|
||||||
) -> Update:
|
) -> Update:
|
||||||
"""Edit ``project_id``; ValueError on bad input, overlap or a past edit.
|
"""Edit ``project_id``; ValueError on bad input, overlap or a past edit.
|
||||||
|
|
||||||
@ -130,13 +130,11 @@ def apply_update(
|
|||||||
if unknown:
|
if unknown:
|
||||||
msg = f"cannot change {unknown}"
|
msg = f"cannot change {unknown}"
|
||||||
raise ValueError(msg)
|
raise ValueError(msg)
|
||||||
today = today or date.today() # noqa: DTZ011
|
today = today or datetime.now(tz=UTC).astimezone().date()
|
||||||
with _store.locked():
|
with _store.locked():
|
||||||
existing = _store.read_all()
|
existing = _store.read_all()
|
||||||
for i, project in enumerate(existing):
|
i = _store.index_of(existing, project_id)
|
||||||
if project.id != project_id:
|
done = _apply(existing[i], changes, today)
|
||||||
continue
|
|
||||||
done = _apply(project, changes, today)
|
|
||||||
edited = done.project
|
edited = done.project
|
||||||
_validate(edited)
|
_validate(edited)
|
||||||
for other in existing:
|
for other in existing:
|
||||||
@ -148,14 +146,13 @@ def apply_update(
|
|||||||
existing[i] = edited
|
existing[i] = edited
|
||||||
_store.write_all(existing)
|
_store.write_all(existing)
|
||||||
return done
|
return done
|
||||||
raise KeyError(project_id)
|
|
||||||
|
|
||||||
|
|
||||||
def update_project(
|
def update_project(
|
||||||
project_id: str,
|
project_id: str,
|
||||||
*,
|
*,
|
||||||
today: date | None = None,
|
today: date | None = None,
|
||||||
**changes: Any, # noqa: ANN401
|
**changes: object,
|
||||||
) -> Project:
|
) -> Project:
|
||||||
""":func:`apply_update` returning just the project."""
|
""":func:`apply_update` returning just the project."""
|
||||||
return apply_update(project_id, today=today, **changes).project
|
return apply_update(project_id, today=today, **changes).project
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import date
|
from datetime import UTC, datetime
|
||||||
import fcntl
|
import fcntl
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
@ -20,7 +20,7 @@ DEVICES = frozenset({"pc", "phone"})
|
|||||||
MAX_SKEW_S = 120.0
|
MAX_SKEW_S = 120.0
|
||||||
|
|
||||||
|
|
||||||
def record_activity( # noqa: PLR0913, PLR0917
|
def record_activity( # pylint: disable=too-many-arguments,too-many-positional-arguments
|
||||||
source: str,
|
source: str,
|
||||||
kind: str,
|
kind: str,
|
||||||
ts: float | None = None,
|
ts: float | None = None,
|
||||||
@ -48,7 +48,7 @@ def record_activity( # noqa: PLR0913, PLR0917
|
|||||||
msg = f"ts is {when - now:.0f} s ahead of the clock (max {MAX_SKEW_S:.0f} s)"
|
msg = f"ts is {when - now:.0f} s ahead of the clock (max {MAX_SKEW_S:.0f} s)"
|
||||||
raise ValueError(msg)
|
raise ValueError(msg)
|
||||||
if project is None:
|
if project is None:
|
||||||
found = _api.active(date.fromtimestamp(when)) # noqa: DTZ012
|
found = _api.active(datetime.fromtimestamp(when, tz=UTC).astimezone().date())
|
||||||
project = found.id if found else None
|
project = found.id if found else None
|
||||||
line = json.dumps(
|
line = json.dumps(
|
||||||
{
|
{
|
||||||
|
|||||||
@ -18,7 +18,7 @@ import logging
|
|||||||
from focus_project import _milestones, _mutate, _store, evidence
|
from focus_project import _milestones, _mutate, _store, evidence
|
||||||
from focus_project._model import Project
|
from focus_project._model import Project
|
||||||
|
|
||||||
_LOG = logging.getLogger(__name__)
|
_logger = logging.getLogger(__name__)
|
||||||
CheckSource = Callable[[Project, datetime], bool | None]
|
CheckSource = Callable[[Project, datetime], bool | None]
|
||||||
DAY_MS = 24 * 3600 * 1000
|
DAY_MS = 24 * 3600 * 1000
|
||||||
# A phone check starts 24 h before the milestone is due.
|
# A phone check starts 24 h before the milestone is due.
|
||||||
@ -48,10 +48,12 @@ def phone_source(project: Project, now: datetime) -> bool | None:
|
|||||||
"""
|
"""
|
||||||
report = evidence.last(evidence.read(project.id), "phone", "phone_check")
|
report = evidence.last(evidence.read(project.id), "phone", "phone_check")
|
||||||
if report is None:
|
if report is None:
|
||||||
_LOG.warning("phone check: no tutor report for %s", project.id)
|
_logger.warning("phone check: no tutor report for %s", project.id)
|
||||||
return None
|
return None
|
||||||
if not 0 <= evidence.to_ms(now) - report.ms <= DAY_MS:
|
if not 0 <= evidence.to_ms(now) - report.ms <= DAY_MS:
|
||||||
_LOG.warning("phone check: tutor report for %s is stale or ahead", project.id)
|
_logger.warning(
|
||||||
|
"phone check: tutor report for %s is stale or ahead", project.id
|
||||||
|
)
|
||||||
return None
|
return None
|
||||||
return _report_ok(report.value, report.ms)
|
return _report_ok(report.value, report.ms)
|
||||||
|
|
||||||
@ -70,8 +72,9 @@ def register_source(name: str, source: CheckSource) -> None:
|
|||||||
def _run(project: Project, now: datetime) -> bool | None:
|
def _run(project: Project, now: datetime) -> bool | None:
|
||||||
try:
|
try:
|
||||||
return SOURCES["phone"](project, now)
|
return SOURCES["phone"](project, now)
|
||||||
except Exception as exc: # noqa: BLE001 (pluggable code: any failure = unknown)
|
# Pluggable code: any failure means unknown, never a crash.
|
||||||
_LOG.warning("phone check source failed: %s", exc)
|
except Exception as exc: # pylint: disable=broad-exception-caught
|
||||||
|
_logger.warning("phone check source failed: %s", exc, exc_info=True)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -17,7 +17,7 @@ carry row pays it from the day's start, own-work rows pay the rest.
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import date, timedelta
|
from datetime import UTC, date, datetime, timedelta
|
||||||
import logging
|
import logging
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
@ -64,7 +64,7 @@ def harvest_day(day: date, now: float) -> int:
|
|||||||
def harvest(now: float | None = None) -> int:
|
def harvest(now: float | None = None) -> int:
|
||||||
"""Harvest the backfill window; 0 on success, 1 if any path failed."""
|
"""Harvest the backfill window; 0 on success, 1 if any path failed."""
|
||||||
moment = _clock.now() if now is None else now
|
moment = _clock.now() if now is None else now
|
||||||
today = date.fromtimestamp(moment) # noqa: DTZ012 (local day)
|
today = datetime.fromtimestamp(moment, tz=UTC).astimezone().date()
|
||||||
try:
|
try:
|
||||||
days = project_days(today)
|
days = project_days(today)
|
||||||
except (RegistryError, OSError) as exc:
|
except (RegistryError, OSError) as exc:
|
||||||
|
|||||||
@ -19,7 +19,7 @@ import os
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import tempfile
|
import tempfile
|
||||||
import time
|
import time
|
||||||
from typing import TYPE_CHECKING, Any, Final
|
from typing import TYPE_CHECKING, Any, Final, TypeIs
|
||||||
|
|
||||||
import earned_time
|
import earned_time
|
||||||
|
|
||||||
@ -93,6 +93,27 @@ def _write_rows(path: Path, rows: list[Any]) -> None:
|
|||||||
Path(handle.name).replace(path)
|
Path(handle.name).replace(path)
|
||||||
|
|
||||||
|
|
||||||
|
def _whole_minutes(value: object) -> TypeIs[int]:
|
||||||
|
"""Whether ``value`` is a positive int minute count (bools excluded)."""
|
||||||
|
return isinstance(value, int) and not isinstance(value, bool) and value >= 1
|
||||||
|
|
||||||
|
|
||||||
|
def _pays_for(
|
||||||
|
row: dict[str, Any],
|
||||||
|
detail: dict[str, Any],
|
||||||
|
project_id: str,
|
||||||
|
day: date,
|
||||||
|
*,
|
||||||
|
carry: bool | None,
|
||||||
|
) -> bool:
|
||||||
|
"""Whether a credit row is for ``project_id`` on ``day`` in class ``carry``."""
|
||||||
|
return (
|
||||||
|
row.get("day") == day.isoformat()
|
||||||
|
and detail.get("project") == project_id
|
||||||
|
and (carry is None or bool(detail.get("carry")) == carry)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def paid_minutes(
|
def paid_minutes(
|
||||||
rows: list[Any],
|
rows: list[Any],
|
||||||
key: bytes,
|
key: bytes,
|
||||||
@ -116,12 +137,8 @@ def paid_minutes(
|
|||||||
continue
|
continue
|
||||||
minutes = detail.get("minutes")
|
minutes = detail.get("minutes")
|
||||||
if (
|
if (
|
||||||
row.get("day") != day.isoformat()
|
not _whole_minutes(minutes)
|
||||||
or detail.get("project") != project_id
|
or not _pays_for(row, detail, project_id, day, carry=carry)
|
||||||
or not isinstance(minutes, int)
|
|
||||||
or isinstance(minutes, bool)
|
|
||||||
or minutes < 1
|
|
||||||
or (carry is not None and bool(detail.get("carry")) != carry)
|
|
||||||
or not earned_time.verified(row, key)
|
or not earned_time.verified(row, key)
|
||||||
):
|
):
|
||||||
continue
|
continue
|
||||||
@ -130,7 +147,7 @@ def paid_minutes(
|
|||||||
return sum(by_id.values())
|
return sum(by_id.values())
|
||||||
|
|
||||||
|
|
||||||
def build_row( # noqa: PLR0913
|
def build_row( # pylint: disable=too-many-arguments
|
||||||
project_id: str,
|
project_id: str,
|
||||||
day: date,
|
day: date,
|
||||||
total: int,
|
total: int,
|
||||||
@ -207,7 +224,7 @@ def credit_to(
|
|||||||
key,
|
key,
|
||||||
now=now or time.time(),
|
now=now or time.time(),
|
||||||
carry=carry,
|
carry=carry,
|
||||||
first_carry=paid == 0,
|
first_carry=not paid,
|
||||||
)
|
)
|
||||||
if any(
|
if any(
|
||||||
isinstance(r, dict) and r.get("entry_id") == row["entry_id"] for r in rows
|
isinstance(r, dict) and r.get("entry_id") == row["entry_id"] for r in rows
|
||||||
|
|||||||
@ -16,14 +16,17 @@ local day up to "now"; carry and the cap play no part. Shown, never paid.
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import date # noqa: TC003
|
|
||||||
import logging
|
import logging
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
from focus_project import _api, _clock, carry, sources
|
from focus_project import _api, _clock, carry, sources
|
||||||
from focus_project._errors import RegistryError
|
from focus_project._errors import RegistryError
|
||||||
from focus_project._own import union_seconds
|
from focus_project._own import union_seconds
|
||||||
from focus_project.sources import activity
|
from focus_project.sources import activity
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
_LOG = logging.getLogger(__name__)
|
_LOG = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -79,7 +79,7 @@ def _open_site(url: str) -> bool:
|
|||||||
return False
|
return False
|
||||||
try:
|
try:
|
||||||
# Not a `with`: the browser must outlive this process.
|
# Not a `with`: the browser must outlive this process.
|
||||||
subprocess.Popen(
|
subprocess.Popen( # pylint: disable=consider-using-with
|
||||||
[opener, url],
|
[opener, url],
|
||||||
stdin=subprocess.DEVNULL,
|
stdin=subprocess.DEVNULL,
|
||||||
stdout=subprocess.DEVNULL,
|
stdout=subprocess.DEVNULL,
|
||||||
|
|||||||
@ -30,7 +30,7 @@ Interval = tuple[float, float]
|
|||||||
# Each heartbeat vouches for the five minutes before it.
|
# Each heartbeat vouches for the five minutes before it.
|
||||||
HEARTBEAT_WINDOW_S = 300.0
|
HEARTBEAT_WINDOW_S = 300.0
|
||||||
ADAPTERS = ("activity", "leetcode", "browser")
|
ADAPTERS = ("activity", "leetcode", "browser")
|
||||||
_LOG = logging.getLogger(__name__)
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def heartbeat_interval(ts: float) -> Interval:
|
def heartbeat_interval(ts: float) -> Interval:
|
||||||
@ -61,19 +61,25 @@ def collect_by_source(day: date, project: Project) -> dict[str, list[Interval]]:
|
|||||||
found: dict[str, list[Interval]] = {}
|
found: dict[str, list[Interval]] = {}
|
||||||
for name in ADAPTERS:
|
for name in ADAPTERS:
|
||||||
module_name = f"{__name__}.{name}"
|
module_name = f"{__name__}.{name}"
|
||||||
|
# A broken adapter must add 0, never stop the others.
|
||||||
try:
|
try:
|
||||||
module = importlib.import_module(module_name)
|
module = importlib.import_module(module_name)
|
||||||
except Exception as exc: # noqa: BLE001 (a broken adapter must add 0)
|
except ModuleNotFoundError as exc:
|
||||||
if isinstance(exc, ModuleNotFoundError) and exc.name == module_name:
|
if exc.name == module_name:
|
||||||
_LOG.info("source %s: not installed (inactive)", name)
|
_logger.info("source %s: not installed (inactive)", name)
|
||||||
continue
|
continue
|
||||||
_LOG.exception("source %s: import failed, contributes 0", name)
|
_logger.exception("source %s: import failed, contributes 0", name)
|
||||||
found[name] = []
|
found[name] = []
|
||||||
continue
|
continue
|
||||||
|
except Exception: # pylint: disable=broad-exception-caught
|
||||||
|
_logger.exception("source %s: import failed, contributes 0", name)
|
||||||
|
found[name] = []
|
||||||
|
continue
|
||||||
|
# Fail closed: this source adds 0.
|
||||||
try:
|
try:
|
||||||
found[name] = clip(list(module.intervals(day, project)), bounds)
|
found[name] = clip(list(module.intervals(day, project)), bounds)
|
||||||
except Exception: # noqa: BLE001 (fail closed: this source adds 0)
|
except Exception: # pylint: disable=broad-exception-caught
|
||||||
_LOG.exception("source %s: failed, contributes 0", name)
|
_logger.exception("source %s: failed, contributes 0", name)
|
||||||
found[name] = []
|
found[name] = []
|
||||||
return found
|
return found
|
||||||
|
|
||||||
|
|||||||
@ -43,7 +43,7 @@ MAX_GAP_S = 600.0
|
|||||||
BACKING_FROM: Final = date(2026, 11, 8)
|
BACKING_FROM: Final = date(2026, 11, 8)
|
||||||
BACKING_SOURCES: Final = frozenset({"tutor", "sql_drills", "leetcode"})
|
BACKING_SOURCES: Final = frozenset({"tutor", "sql_drills", "leetcode"})
|
||||||
BRIDGE_S: Final = 1200.0
|
BRIDGE_S: Final = 1200.0
|
||||||
_LOG = logging.getLogger(__name__)
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def read_events(project_id: str) -> list[dict[str, Any]]:
|
def read_events(project_id: str) -> list[dict[str, Any]]:
|
||||||
@ -67,7 +67,7 @@ def read_events(project_id: str) -> list[dict[str, Any]]:
|
|||||||
if ok:
|
if ok:
|
||||||
events.append(row)
|
events.append(row)
|
||||||
elif line.strip():
|
elif line.strip():
|
||||||
_LOG.debug("activity line skipped: %.80s", line)
|
_logger.debug("activity line skipped: %.80s", line)
|
||||||
events.sort(key=lambda e: e["ts"])
|
events.sort(key=lambda e: e["ts"])
|
||||||
return events
|
return events
|
||||||
|
|
||||||
@ -127,8 +127,9 @@ def backing_times(events: list[dict[str, Any]], project: Project) -> list[float]
|
|||||||
# working (heartbeat backing only) where that is not installed.
|
# working (heartbeat backing only) where that is not installed.
|
||||||
leetcode = importlib.import_module("focus_project.sources.leetcode")
|
leetcode = importlib.import_module("focus_project.sources.leetcode")
|
||||||
times += leetcode.submission_times(project)
|
times += leetcode.submission_times(project)
|
||||||
except Exception: # noqa: BLE001 (lose the submissions, keep the beats)
|
# Lose the submissions, keep the beats.
|
||||||
_LOG.exception("leetcode backing unavailable, heartbeats only")
|
except Exception: # pylint: disable=broad-exception-caught
|
||||||
|
_logger.exception("leetcode backing unavailable, heartbeats only")
|
||||||
return sorted(times)
|
return sorted(times)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -25,7 +25,7 @@ import json
|
|||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import TYPE_CHECKING, Any
|
from typing import TYPE_CHECKING, Any, cast
|
||||||
from urllib.parse import urlencode
|
from urllib.parse import urlencode
|
||||||
from urllib.request import Request, urlopen
|
from urllib.request import Request, urlopen
|
||||||
|
|
||||||
@ -78,10 +78,10 @@ def _config() -> Config | None:
|
|||||||
return Config(url.rstrip("/"), values.get("KT_TOKEN", "")) if url else None
|
return Config(url.rstrip("/"), values.get("KT_TOKEN", "")) if url else None
|
||||||
|
|
||||||
|
|
||||||
def _get_json(cfg: Config, path: str, params: dict[str, str] | None = None) -> Any: # noqa: ANN401
|
def _get_json(cfg: Config, path: str, params: dict[str, str] | None = None) -> object:
|
||||||
"""One authenticated GET returning parsed JSON."""
|
"""One authenticated GET returning parsed JSON."""
|
||||||
url = cfg.url + path + (f"?{urlencode(params)}" if params else "")
|
url = cfg.url + path + (f"?{urlencode(params)}" if params else "")
|
||||||
request = Request(url) # noqa: S310 (operator-configured http URL)
|
request = Request(url)
|
||||||
if cfg.token:
|
if cfg.token:
|
||||||
request.add_header("Authorization", f"Bearer {cfg.token}")
|
request.add_header("Authorization", f"Bearer {cfg.token}")
|
||||||
with _urlopen(request, timeout=TIMEOUT_S) as response:
|
with _urlopen(request, timeout=TIMEOUT_S) as response:
|
||||||
@ -158,17 +158,14 @@ def intervals(day: date, project: Project) -> list[Interval]:
|
|||||||
if cfg is None:
|
if cfg is None:
|
||||||
_LOG.info("browser source: no kuhytrack config (inactive)")
|
_LOG.info("browser source: no kuhytrack config (inactive)")
|
||||||
return []
|
return []
|
||||||
lo, hi = day_bounds(day)
|
params = _window(day)
|
||||||
stamp = "%Y-%m-%dT%H:%M:%S.000Z"
|
|
||||||
params = {
|
|
||||||
"start": datetime.fromtimestamp(lo - LOOKBACK_S, UTC).strftime(stamp),
|
|
||||||
"end": datetime.fromtimestamp(hi, UTC).strftime(stamp),
|
|
||||||
}
|
|
||||||
|
|
||||||
def events(bucket: dict[str, Any]) -> list[dict[str, Any]]:
|
def events(bucket: dict[str, Any]) -> list[dict[str, Any]]:
|
||||||
return list(_get_json(cfg, f"/api/0/buckets/{bucket['id']}/events", params))
|
path = f"/api/0/buckets/{bucket['id']}/events"
|
||||||
|
return list(cast("list[dict[str, Any]]", _get_json(cfg, path, params)))
|
||||||
|
|
||||||
buckets = list(_get_json(cfg, "/api/0/buckets").values())
|
found = cast("dict[str, dict[str, Any]]", _get_json(cfg, "/api/0/buckets"))
|
||||||
|
buckets = list(found.values())
|
||||||
present: dict[str, list[Interval]] = {}
|
present: dict[str, list[Interval]] = {}
|
||||||
for bucket in buckets:
|
for bucket in buckets:
|
||||||
if bucket["type"] == "afkstatus":
|
if bucket["type"] == "afkstatus":
|
||||||
@ -179,6 +176,23 @@ def intervals(day: date, project: Project) -> list[Interval]:
|
|||||||
if bucket["type"] == "currentwindow":
|
if bucket["type"] == "currentwindow":
|
||||||
hits = [e for e in events(bucket) if _matches(e["data"], full, stems)]
|
hits = [e for e in events(bucket) if _matches(e["data"], full, stems)]
|
||||||
on_site.setdefault(bucket["hostname"], []).extend(_spans(hits))
|
on_site.setdefault(bucket["hostname"], []).extend(_spans(hits))
|
||||||
|
return _present_on_site(on_site, present)
|
||||||
|
|
||||||
|
|
||||||
|
def _window(day: date) -> dict[str, str]:
|
||||||
|
"""The tracker query range: ``day`` plus :data:`LOOKBACK_S` before it."""
|
||||||
|
lo, hi = day_bounds(day)
|
||||||
|
stamp = "%Y-%m-%dT%H:%M:%S.000Z"
|
||||||
|
return {
|
||||||
|
"start": datetime.fromtimestamp(lo - LOOKBACK_S, UTC).strftime(stamp),
|
||||||
|
"end": datetime.fromtimestamp(hi, UTC).strftime(stamp),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _present_on_site(
|
||||||
|
on_site: dict[str, list[Interval]], present: dict[str, list[Interval]]
|
||||||
|
) -> list[Interval]:
|
||||||
|
"""Each host's site time trimmed to its presence (no AFK bucket: present)."""
|
||||||
out: list[Interval] = []
|
out: list[Interval] = []
|
||||||
for host, spans in on_site.items():
|
for host, spans in on_site.items():
|
||||||
merged = _merge(spans)
|
merged = _merge(spans)
|
||||||
|
|||||||
@ -49,8 +49,10 @@ def _submitted_at(row: object, key: bytes) -> float | None:
|
|||||||
):
|
):
|
||||||
return None
|
return None
|
||||||
detail = row.get("detail")
|
detail = row.get("detail")
|
||||||
|
if not isinstance(detail, dict):
|
||||||
|
return None
|
||||||
try:
|
try:
|
||||||
return float(detail["submitted_at"]) # type: ignore[index]
|
return float(detail["submitted_at"])
|
||||||
except KeyError, TypeError, ValueError:
|
except KeyError, TypeError, ValueError:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@ -67,6 +69,7 @@ def submission_times(project: Project) -> list[float]:
|
|||||||
return [ts for ts in stamps if ts is not None]
|
return [ts for ts in stamps if ts is not None]
|
||||||
|
|
||||||
|
|
||||||
def intervals(day: date, project: Project) -> list[Interval]: # noqa: ARG001
|
def intervals(day: date, project: Project) -> list[Interval]:
|
||||||
"""One heartbeat per accepted submission (the registry clips to the day)."""
|
"""One heartbeat per accepted submission (the registry clips to the day)."""
|
||||||
|
del day # the adapter signature takes the day; the registry does the clipping
|
||||||
return [heartbeat_interval(ts) for ts in submission_times(project)]
|
return [heartbeat_interval(ts) for ts in submission_times(project)]
|
||||||
|
|||||||
@ -5,7 +5,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from datetime import date, datetime, time, timedelta
|
from datetime import date, datetime, time, timedelta
|
||||||
import json
|
import json
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
import focus_project as fp
|
import focus_project as fp
|
||||||
from focus_project._paths import activity_path
|
from focus_project._paths import activity_path
|
||||||
@ -27,7 +27,7 @@ def at(day: int, hour: int = 0, minute: int = 0) -> datetime:
|
|||||||
|
|
||||||
def make(pid: str = "iv", /, **kw: object) -> fp.Project:
|
def make(pid: str = "iv", /, **kw: object) -> fp.Project:
|
||||||
"""Create an interview project D1 = Nov 10, T = Nov 27."""
|
"""Create an interview project D1 = Nov 10, T = Nov 27."""
|
||||||
args: dict[str, object] = {
|
args: dict[str, Any] = {
|
||||||
"name": "Interview",
|
"name": "Interview",
|
||||||
"start": START,
|
"start": START,
|
||||||
"end": TEST_DAY,
|
"end": TEST_DAY,
|
||||||
@ -39,7 +39,7 @@ def make(pid: str = "iv", /, **kw: object) -> fp.Project:
|
|||||||
"invite_url": "https://app.codility.com/c/run/abc",
|
"invite_url": "https://app.codility.com/c/run/abc",
|
||||||
}
|
}
|
||||||
args.update(kw)
|
args.update(kw)
|
||||||
return fp.create_project(pid, **args) # type: ignore[arg-type]
|
return fp.create_project(pid, **args)
|
||||||
|
|
||||||
|
|
||||||
def shot(tmp_path: Path, name: str = "rules.png") -> Path:
|
def shot(tmp_path: Path, name: str = "rules.png") -> Path:
|
||||||
@ -3,12 +3,12 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import date, datetime
|
from datetime import UTC, date, datetime
|
||||||
import importlib
|
import importlib
|
||||||
import json
|
import json
|
||||||
from pathlib import Path # noqa: TC003
|
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
@ -16,6 +16,9 @@ import focus_project as fp
|
|||||||
from focus_project import _clock
|
from focus_project import _clock
|
||||||
from focus_project._paths import data_dir
|
from focus_project._paths import data_dir
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
D1 = date(2026, 11, 2)
|
D1 = date(2026, 11, 2)
|
||||||
|
|
||||||
|
|
||||||
@ -64,7 +67,7 @@ def test_record_activity_defaults_now_and_project(
|
|||||||
data: Path, monkeypatch: pytest.MonkeyPatch
|
data: Path, monkeypatch: pytest.MonkeyPatch
|
||||||
) -> None:
|
) -> None:
|
||||||
monkeypatch.setattr(_clock, "now", time.time) # the real clock, once
|
monkeypatch.setattr(_clock, "now", time.time) # the real clock, once
|
||||||
today = date.today() # noqa: DTZ011
|
today = datetime.now(tz=UTC).astimezone().date()
|
||||||
fp.create_project(
|
fp.create_project(
|
||||||
"now",
|
"now",
|
||||||
name="n",
|
name="n",
|
||||||
@ -96,9 +99,9 @@ def test_record_activity_no_project_when_none_active(data: Path) -> None:
|
|||||||
{"source": "timer", "kind": "start", "dev": "tv"},
|
{"source": "timer", "kind": "start", "dev": "tv"},
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
def test_record_activity_validation(kw: dict[str, str], data: Path) -> None:
|
def test_record_activity_validation(kw: dict[str, Any], data: Path) -> None:
|
||||||
with pytest.raises(ValueError, match="unknown"):
|
with pytest.raises(ValueError, match="unknown"):
|
||||||
fp.record_activity(**kw) # type: ignore[arg-type]
|
fp.record_activity(**kw)
|
||||||
assert not (data / "activity.jsonl").exists()
|
assert not (data / "activity.jsonl").exists()
|
||||||
|
|
||||||
|
|
||||||
@ -186,4 +189,4 @@ def test_a_timestamp_far_ahead_is_rejected(
|
|||||||
def test_the_real_clock_seam_reads_wall_time() -> None:
|
def test_the_real_clock_seam_reads_wall_time() -> None:
|
||||||
importlib.reload(_clock) # undo the autouse pin on the module attribute
|
importlib.reload(_clock) # undo the autouse pin on the module attribute
|
||||||
assert abs(_clock.now() - time.time()) < 5
|
assert abs(_clock.now() - time.time()) < 5
|
||||||
assert _clock.today() == date.today() # noqa: DTZ011
|
assert _clock.today() == datetime.now(tz=UTC).astimezone().date()
|
||||||
|
|||||||
@ -5,7 +5,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from datetime import date, datetime, timedelta
|
from datetime import date, datetime, timedelta
|
||||||
import json
|
import json
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING, Any
|
||||||
from unittest import mock
|
from unittest import mock
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
@ -24,14 +24,14 @@ D4 = date(2026, 11, 5)
|
|||||||
def _make(
|
def _make(
|
||||||
pid: str = "hr", start: date = D1, end: date = D4, **kw: object
|
pid: str = "hr", start: date = D1, end: date = D4, **kw: object
|
||||||
) -> fp.Project:
|
) -> fp.Project:
|
||||||
args: dict[str, object] = {
|
args: dict[str, Any] = {
|
||||||
"name": "HackerRank prep",
|
"name": "HackerRank prep",
|
||||||
"replaces": ["leetcode", "reading", "tutor"],
|
"replaces": ["leetcode", "reading", "tutor"],
|
||||||
"daily_minutes": 120,
|
"daily_minutes": 120,
|
||||||
"unlock_minutes": 30,
|
"unlock_minutes": 30,
|
||||||
}
|
}
|
||||||
args.update(kw)
|
args.update(kw)
|
||||||
return fp.create_project(pid, start=start, end=end, **args) # type: ignore[arg-type]
|
return fp.create_project(pid, start=start, end=end, **args)
|
||||||
|
|
||||||
|
|
||||||
def test_empty_registry() -> None:
|
def test_empty_registry() -> None:
|
||||||
@ -57,8 +57,10 @@ def test_create_roundtrip_and_file_shape(data: Path) -> None:
|
|||||||
def test_active_boundaries() -> None:
|
def test_active_boundaries() -> None:
|
||||||
_make()
|
_make()
|
||||||
assert fp.active(D1 - timedelta(days=1)) is None
|
assert fp.active(D1 - timedelta(days=1)) is None
|
||||||
assert fp.active(D1).id == "hr" # type: ignore[union-attr]
|
for day in (D1, D4):
|
||||||
assert fp.active(D4).id == "hr" # type: ignore[union-attr]
|
found = fp.active(day)
|
||||||
|
assert found is not None
|
||||||
|
assert found.id == "hr"
|
||||||
assert fp.active(D4 + timedelta(days=1)) is None
|
assert fp.active(D4 + timedelta(days=1)) is None
|
||||||
|
|
||||||
|
|
||||||
@ -141,9 +143,9 @@ def test_end_project_errors() -> None:
|
|||||||
({"name": " "}, "name"),
|
({"name": " "}, "name"),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
def test_create_validation(kw: dict[str, object], match: str) -> None:
|
def test_create_validation(kw: dict[str, Any], match: str) -> None:
|
||||||
with pytest.raises(ValueError, match=match):
|
with pytest.raises(ValueError, match=match):
|
||||||
_make(**kw) # type: ignore[arg-type]
|
_make(**kw)
|
||||||
assert fp.list_projects() == []
|
assert fp.list_projects() == []
|
||||||
|
|
||||||
|
|
||||||
@ -185,7 +187,7 @@ def test_failed_write_keeps_old_file(data: Path) -> None:
|
|||||||
_make()
|
_make()
|
||||||
before = (data / "projects.json").read_text()
|
before = (data / "projects.json").read_text()
|
||||||
with (
|
with (
|
||||||
mock.patch("focus_project._store.os.replace", side_effect=OSError("boom")),
|
mock.patch("focus_project._store.Path.replace", side_effect=OSError("boom")),
|
||||||
pytest.raises(OSError, match="boom"),
|
pytest.raises(OSError, match="boom"),
|
||||||
):
|
):
|
||||||
_make("two", start=D4 + timedelta(days=3), end=D4 + timedelta(days=4))
|
_make("two", start=D4 + timedelta(days=3), end=D4 + timedelta(days=4))
|
||||||
|
|||||||
@ -5,8 +5,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from datetime import date, timedelta
|
from datetime import date, timedelta
|
||||||
import json
|
import json
|
||||||
from pathlib import Path # noqa: TC003
|
from typing import TYPE_CHECKING, Any
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
import earned_time
|
import earned_time
|
||||||
import pytest
|
import pytest
|
||||||
@ -15,6 +14,9 @@ import focus_project as fp
|
|||||||
from focus_project import carry, harvest, ledger, minutes
|
from focus_project import carry, harvest, ledger, minutes
|
||||||
from focus_project.tests.test_minutes import D1, at, events, project
|
from focus_project.tests.test_minutes import D1, at, events, project
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
KEY = b"k" * 32
|
KEY = b"k" * 32
|
||||||
D2 = D1 + timedelta(days=1)
|
D2 = D1 + timedelta(days=1)
|
||||||
D3 = D2 + timedelta(days=1)
|
D3 = D2 + timedelta(days=1)
|
||||||
|
|||||||
@ -4,13 +4,13 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
import focus_project as fp
|
import focus_project as fp
|
||||||
from focus_project import _paths, checks, evidence
|
from focus_project import _paths, checks, evidence
|
||||||
from focus_project.tests.helpers import SAT1, at, make
|
from focus_project.tests._helpers import SAT1, at, make
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
@ -57,9 +57,9 @@ def test_phone_source_passes_on_a_fresh_good_report() -> None:
|
|||||||
"bad",
|
"bad",
|
||||||
[{"plan": False}, {"due": 0}, {"seen": at(11, 7)}],
|
[{"plan": False}, {"due": 0}, {"seen": at(11, 7)}],
|
||||||
)
|
)
|
||||||
def test_phone_source_fails_on_any_bad_part(bad: dict[str, object]) -> None:
|
def test_phone_source_fails_on_any_bad_part(bad: dict[str, Any]) -> None:
|
||||||
make()
|
make()
|
||||||
_report(at(13, 8), **bad) # type: ignore[arg-type]
|
_report(at(13, 8), **bad)
|
||||||
assert _phone(at(13, 9)) is False
|
assert _phone(at(13, 9)) is False
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -10,7 +10,7 @@ import pytest
|
|||||||
|
|
||||||
import focus_project as fp
|
import focus_project as fp
|
||||||
from focus_project import _paths, evidence
|
from focus_project import _paths, evidence
|
||||||
from focus_project.tests.helpers import at, make, shot
|
from focus_project.tests._helpers import at, make, shot
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@ -50,28 +50,35 @@ def test_same_name_files_do_not_overwrite(tmp_path: Path) -> None:
|
|||||||
assert one.value != two.value
|
assert one.value != two.value
|
||||||
|
|
||||||
|
|
||||||
|
_KINDS = "takes evidence kinds"
|
||||||
|
_SCORE = "a score must be a finite, non-negative number"
|
||||||
|
_PHONE = "phone_check needs"
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
("milestone", "kind", "value"),
|
("milestone", "kind", "value", "match"),
|
||||||
[
|
[
|
||||||
("rules", "tap", True), # wrong kind for the milestone
|
("rules", "tap", True, _KINDS), # wrong kind for the milestone
|
||||||
("rules", "check", True), # internal kind
|
("rules", "check", True, _KINDS), # internal kind
|
||||||
("trip_ask:2026-11-14", "answer", True), # use answer_weekend
|
("trip_ask:2026-11-14", "answer", True, _KINDS), # use answer_weekend
|
||||||
("nope", "tap", True), # not a milestone of the project
|
("nope", "tap", True, "is not a milestone of"), # not of the project
|
||||||
("mock", "score", "high"),
|
("mock", "score", "high", _SCORE),
|
||||||
("mock", "score", True),
|
("mock", "score", True, _SCORE),
|
||||||
("mock", "score", float("nan")),
|
("mock", "score", float("nan"), _SCORE),
|
||||||
("mock", "score", -1),
|
("mock", "score", -1, _SCORE),
|
||||||
("slot", "slot", "tomorrow"),
|
("slot", "slot", "tomorrow", "Invalid isoformat string"),
|
||||||
("slot", "slot", "2026-11-26T10:00:00+02:00"), # aware
|
("slot", "slot", "2026-11-26T10:00:00+02:00", "naive local"), # aware
|
||||||
("slot", "slot_confirm", False),
|
("slot", "slot_confirm", False, "slot_confirm is a tap"),
|
||||||
("phone", "phone_check", {"plan": True}),
|
("phone", "phone_check", {"plan": True}, "due must be a non-negative"),
|
||||||
("phone", "phone_check", {"plan": "yes", "due": 1, "seen_ms": 1}),
|
("phone", "phone_check", {"plan": "yes", "due": 1, "seen_ms": 1}, _PHONE),
|
||||||
("phone", "phone_check", "ok"),
|
("phone", "phone_check", "ok", _PHONE),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
def test_bad_evidence_refused(milestone: str, kind: str, value: object) -> None:
|
def test_bad_evidence_refused(
|
||||||
|
milestone: str, kind: str, value: object, match: str
|
||||||
|
) -> None:
|
||||||
make()
|
make()
|
||||||
with pytest.raises(ValueError): # noqa: PT011
|
with pytest.raises(ValueError, match=match):
|
||||||
fp.record_evidence("iv", milestone, kind, value, now=at(12, 9))
|
fp.record_evidence("iv", milestone, kind, value, now=at(12, 9))
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -4,7 +4,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import date, timedelta
|
from datetime import date, timedelta
|
||||||
from pathlib import Path # noqa: TC003
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
@ -13,6 +13,9 @@ from focus_project import harvest, ledger
|
|||||||
from focus_project.tests.test_ledger_harvest import KEY, rows
|
from focus_project.tests.test_ledger_harvest import KEY, rows
|
||||||
from focus_project.tests.test_minutes import D1, at, events
|
from focus_project.tests.test_minutes import D1, at, events
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
@pytest.fixture(autouse=True)
|
||||||
def _key(tmp_path: Path) -> None:
|
def _key(tmp_path: Path) -> None:
|
||||||
|
|||||||
@ -12,7 +12,7 @@ import pytest
|
|||||||
import focus_project as fp
|
import focus_project as fp
|
||||||
from focus_project import _interview, _milestones
|
from focus_project import _interview, _milestones
|
||||||
from focus_project._errors import RegistryError
|
from focus_project._errors import RegistryError
|
||||||
from focus_project.tests.helpers import SAT1, START, TEST_AT, TEST_DAY, at, make
|
from focus_project.tests._helpers import SAT1, START, TEST_AT, TEST_DAY, at, make
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@ -80,25 +80,30 @@ def test_interview_roundtrip_and_file_shape(data: Path) -> None:
|
|||||||
assert row["invite_url"].startswith("https://")
|
assert row["invite_url"].startswith("https://")
|
||||||
|
|
||||||
|
|
||||||
|
_URL = "invite_url must be an http"
|
||||||
|
_TRIP = "must start by the test day"
|
||||||
|
_WEEKEND = "is not a weekend inside the project"
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
"bad",
|
("bad", "match"),
|
||||||
[
|
[
|
||||||
{"test_at": None},
|
({"test_at": None}, "needs test_at"),
|
||||||
{"test_at": at(26, 10)}, # end != test day
|
({"test_at": at(26, 10)}, "end must be the test day"), # end != test day
|
||||||
{"test_at": at(9, 10), "end": date(2026, 11, 9)},
|
({"test_at": at(9, 10), "end": date(2026, 11, 9)}, "end is before start"),
|
||||||
{"invite_url": "ftp://x.example/t"},
|
({"invite_url": "ftp://x.example/t"}, _URL),
|
||||||
{"invite_url": "javascript:alert(1)"},
|
({"invite_url": "javascript:alert(1)"}, _URL),
|
||||||
{"invite_url": "https://a b.example"},
|
({"invite_url": "https://a b.example"}, _URL),
|
||||||
{"kind": "bogus"},
|
({"kind": "bogus"}, "kind must be one of"),
|
||||||
{"trips": [fp.Trip(date(2026, 11, 28), date(2026, 11, 29))]},
|
({"trips": [fp.Trip(date(2026, 11, 28), date(2026, 11, 29))]}, _TRIP),
|
||||||
{"trips": [fp.Trip(date(2026, 11, 20), date(2026, 11, 19))]},
|
({"trips": [fp.Trip(date(2026, 11, 20), date(2026, 11, 19))]}, _TRIP),
|
||||||
{"weekend_answers": {date(2026, 11, 15): True}}, # a Sunday
|
({"weekend_answers": {date(2026, 11, 15): True}}, _WEEKEND), # a Sunday
|
||||||
{"weekend_answers": {date(2026, 11, 28): True}}, # after T
|
({"weekend_answers": {date(2026, 11, 28): True}}, _WEEKEND), # after T
|
||||||
{"daily_minutes": 29},
|
({"daily_minutes": 29}, "daily_minutes must be at least 30"),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
def test_interview_validation(bad: dict[str, object]) -> None:
|
def test_interview_validation(bad: dict[str, object], match: str) -> None:
|
||||||
with pytest.raises(ValueError): # noqa: PT011
|
with pytest.raises(ValueError, match=match):
|
||||||
make(**bad)
|
make(**bad)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -6,8 +6,7 @@ from __future__ import annotations
|
|||||||
from datetime import date, timedelta
|
from datetime import date, timedelta
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
from pathlib import Path # noqa: TC003
|
from typing import TYPE_CHECKING, Any
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
import earned_time
|
import earned_time
|
||||||
import pytest
|
import pytest
|
||||||
@ -16,6 +15,9 @@ import focus_project as fp
|
|||||||
from focus_project import harvest, ledger, minutes
|
from focus_project import harvest, ledger, minutes
|
||||||
from focus_project.tests.test_minutes import D1, at, events, project
|
from focus_project.tests.test_minutes import D1, at, events, project
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
KEY = b"k" * 32
|
KEY = b"k" * 32
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -8,7 +8,7 @@ from typing import TYPE_CHECKING
|
|||||||
|
|
||||||
import focus_project as fp
|
import focus_project as fp
|
||||||
from focus_project import evidence
|
from focus_project import evidence
|
||||||
from focus_project.tests.helpers import SAT1, SAT2, at, make, session, shot, states
|
from focus_project.tests._helpers import SAT1, SAT2, at, make, session, shot, states
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|||||||
@ -4,7 +4,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import focus_project as fp
|
import focus_project as fp
|
||||||
from focus_project.tests.helpers import at, make, session, states
|
from focus_project.tests._helpers import at, make, session, states
|
||||||
|
|
||||||
|
|
||||||
def test_mock_needs_a_score_after_a_long_session() -> None:
|
def test_mock_needs_a_score_after_a_long_session() -> None:
|
||||||
|
|||||||
@ -9,7 +9,7 @@ import stat
|
|||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
@ -43,6 +43,7 @@ def stubs(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> dict[str, Path]:
|
|||||||
|
|
||||||
|
|
||||||
def _project(**fields: object) -> None:
|
def _project(**fields: object) -> None:
|
||||||
|
extra: dict[str, Any] = dict(fields)
|
||||||
fp.create_project(
|
fp.create_project(
|
||||||
"hr",
|
"hr",
|
||||||
name="HackerRank prep",
|
name="HackerRank prep",
|
||||||
@ -52,7 +53,7 @@ def _project(**fields: object) -> None:
|
|||||||
daily_minutes=120,
|
daily_minutes=120,
|
||||||
unlock_minutes=30,
|
unlock_minutes=30,
|
||||||
site_patterns=["leetcode.com", "hackerrank.com"],
|
site_patterns=["leetcode.com", "hackerrank.com"],
|
||||||
**fields, # type: ignore[arg-type]
|
**extra,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -9,7 +9,7 @@ import pytest
|
|||||||
|
|
||||||
import focus_project as fp
|
import focus_project as fp
|
||||||
from focus_project import evidence
|
from focus_project import evidence
|
||||||
from focus_project.tests.helpers import SAT1, at, make, states
|
from focus_project.tests._helpers import SAT1, at, make, states
|
||||||
|
|
||||||
|
|
||||||
def _ms(day: int, hour: int) -> int:
|
def _ms(day: int, hour: int) -> int:
|
||||||
@ -69,7 +69,7 @@ def test_trip_may_not_shrink_or_start_later(start: date, end: date) -> None:
|
|||||||
)
|
)
|
||||||
def test_bad_trip_ranges(start: date, end: date) -> None:
|
def test_bad_trip_ranges(start: date, end: date) -> None:
|
||||||
make()
|
make()
|
||||||
with pytest.raises(ValueError): # noqa: PT011
|
with pytest.raises(ValueError, match="must start by the test day"):
|
||||||
fp.add_trip("iv", start, end, now=at(10, 9))
|
fp.add_trip("iv", start, end, now=at(10, 9))
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -53,7 +53,7 @@ def _fake_tracker(
|
|||||||
|
|
||||||
def fake(
|
def fake(
|
||||||
_cfg: browser.Config, path: str, params: dict[str, str] | None = None
|
_cfg: browser.Config, path: str, params: dict[str, str] | None = None
|
||||||
) -> Any: # noqa: ANN401
|
) -> object:
|
||||||
calls.append((path, params))
|
calls.append((path, params))
|
||||||
if path == "/api/0/buckets":
|
if path == "/api/0/buckets":
|
||||||
return {b["id"]: b for b in buckets}
|
return {b["id"]: b for b in buckets}
|
||||||
|
|||||||
@ -10,6 +10,7 @@ from focus_project.sources import browser
|
|||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from urllib.request import Request
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
@ -42,7 +43,7 @@ def test_config_without_url_is_none(
|
|||||||
def test_get_json_sends_bearer_and_query(monkeypatch: pytest.MonkeyPatch) -> None:
|
def test_get_json_sends_bearer_and_query(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
seen: dict[str, Any] = {}
|
seen: dict[str, Any] = {}
|
||||||
|
|
||||||
def fake_open(req: Any, timeout: float) -> io.BytesIO: # noqa: ANN401
|
def fake_open(req: Request, timeout: float) -> io.BytesIO:
|
||||||
seen["url"] = req.full_url
|
seen["url"] = req.full_url
|
||||||
seen["auth"] = req.get_header("Authorization")
|
seen["auth"] = req.get_header("Authorization")
|
||||||
seen["timeout"] = timeout
|
seen["timeout"] = timeout
|
||||||
@ -62,7 +63,7 @@ def test_get_json_without_token_sends_no_header(
|
|||||||
) -> None:
|
) -> None:
|
||||||
seen: dict[str, Any] = {}
|
seen: dict[str, Any] = {}
|
||||||
|
|
||||||
def fake_open(req: Any, timeout: float) -> io.BytesIO: # noqa: ANN401
|
def fake_open(req: Request, timeout: float) -> io.BytesIO:
|
||||||
seen["auth"] = req.get_header("Authorization")
|
seen["auth"] = req.get_header("Authorization")
|
||||||
return io.BytesIO(b"[]")
|
return io.BytesIO(b"[]")
|
||||||
|
|
||||||
|
|||||||
@ -35,7 +35,7 @@ def _fake(
|
|||||||
fn: Callable[[date, Project], list[sources.Interval]],
|
fn: Callable[[date, Project], list[sources.Interval]],
|
||||||
) -> None:
|
) -> None:
|
||||||
module = types.ModuleType(f"focus_project.sources.{name}")
|
module = types.ModuleType(f"focus_project.sources.{name}")
|
||||||
module.intervals = fn # type: ignore[attr-defined]
|
vars(module)["intervals"] = fn
|
||||||
monkeypatch.setitem(sys.modules, f"focus_project.sources.{name}", module)
|
monkeypatch.setitem(sys.modules, f"focus_project.sources.{name}", module)
|
||||||
|
|
||||||
|
|
||||||
@ -106,3 +106,17 @@ def test_broken_adapter_import_contributes_zero(
|
|||||||
assert all(spans == [] for spans in result.values())
|
assert all(spans == [] for spans in result.values())
|
||||||
assert set(result) == set(sources.ADAPTERS)
|
assert set(result) == set(sources.ADAPTERS)
|
||||||
assert "import failed" in caplog.text
|
assert "import failed" in caplog.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_adapter_missing_a_dependency_contributes_zero(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||||
|
) -> None:
|
||||||
|
def missing_dep(name: str) -> None:
|
||||||
|
msg = "No module named 'some_dep'"
|
||||||
|
raise ModuleNotFoundError(msg, name="some_dep")
|
||||||
|
|
||||||
|
monkeypatch.setattr("focus_project.sources.importlib.import_module", missing_dep)
|
||||||
|
with caplog.at_level(logging.ERROR):
|
||||||
|
result = sources.collect_by_source(DAY, PROJECT)
|
||||||
|
assert result == {key: [] for key in sources.ADAPTERS}
|
||||||
|
assert "import failed" in caplog.text
|
||||||
|
|||||||
@ -8,7 +8,7 @@ from typing import TYPE_CHECKING
|
|||||||
|
|
||||||
import focus_project as fp
|
import focus_project as fp
|
||||||
from focus_project import _clock, evidence
|
from focus_project import _clock, evidence
|
||||||
from focus_project.tests.helpers import at, make
|
from focus_project.tests._helpers import at, make
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import date, timedelta
|
from datetime import UTC, date, datetime, timedelta
|
||||||
import json
|
import json
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
@ -57,7 +57,7 @@ def test_update_nothing_is_a_noop() -> None:
|
|||||||
|
|
||||||
|
|
||||||
def test_update_defaults_today_to_real_today() -> None:
|
def test_update_defaults_today_to_real_today() -> None:
|
||||||
now = date.today() # noqa: DTZ011
|
now = datetime.now(tz=UTC).astimezone().date()
|
||||||
_make("now", start=now, end=now + DAY)
|
_make("now", start=now, end=now + DAY)
|
||||||
assert fp.update_project("now", name="X").name == "X"
|
assert fp.update_project("now", name="X").name == "X"
|
||||||
|
|
||||||
|
|||||||
@ -8,7 +8,7 @@ version = "0.10.0"
|
|||||||
description = "Time-boxed focus projects: replace chosen gates, pay a daily-minutes gate"
|
description = "Time-boxed focus projects: replace chosen gates, pay a daily-minutes gate"
|
||||||
requires-python = ">=3.14"
|
requires-python = ">=3.14"
|
||||||
# Stdlib only on purpose: guards import it from the system python.
|
# Stdlib only on purpose: guards import it from the system python.
|
||||||
dependencies = []
|
dependencies = ["earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.21.0#subdirectory=earned_time"]
|
||||||
|
|
||||||
[tool.setuptools.packages.find]
|
[tool.setuptools.packages.find]
|
||||||
include = ["focus_project*"]
|
include = ["focus_project*"]
|
||||||
@ -36,6 +36,16 @@ unfixable = []
|
|||||||
[tool.ruff.lint.per-file-ignores]
|
[tool.ruff.lint.per-file-ignores]
|
||||||
"**/tests/**/*.py" = ["ARG", "D", "PLC0415", "PLR2004", "S101", "SLF001"]
|
"**/tests/**/*.py" = ["ARG", "D", "PLC0415", "PLR2004", "S101", "SLF001"]
|
||||||
"**/test_*.py" = ["ARG", "D", "PLC0415", "PLR2004", "S101", "SLF001"]
|
"**/test_*.py" = ["ARG", "D", "PLC0415", "PLR2004", "S101", "SLF001"]
|
||||||
|
# Public API that focus-guard (and its e2e scripts) call by keyword: these
|
||||||
|
# signatures mirror Project's fields, so cutting arguments means a breaking
|
||||||
|
# release across the consumers. The matching pylint disables sit on each def.
|
||||||
|
"focus_project/_api.py" = ["PLR0913"]
|
||||||
|
"focus_project/_mutate.py" = ["PLR0913"]
|
||||||
|
"focus_project/activity.py" = ["PLR0913", "PLR0917"]
|
||||||
|
"focus_project/ledger.py" = ["PLR0913"]
|
||||||
|
# The browser source's base URL is operator config (an http:// localhost
|
||||||
|
# extension bridge), never user input, so urllib's scheme check is moot.
|
||||||
|
"focus_project/sources/browser.py" = ["S310"]
|
||||||
|
|
||||||
[tool.ruff.lint.pydocstyle]
|
[tool.ruff.lint.pydocstyle]
|
||||||
convention = "google"
|
convention = "google"
|
||||||
|
|||||||
@ -2,9 +2,10 @@
|
|||||||
# floor is satisfied by anything newer, so it tells a checker nothing
|
# floor is satisfied by anything newer, so it tells a checker nothing
|
||||||
# about whether this repo is actually current.
|
# about whether this repo is actually current.
|
||||||
bandit[toml]==1.9.4
|
bandit[toml]==1.9.4
|
||||||
|
earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.21.0#subdirectory=earned_time
|
||||||
mypy==2.4.1
|
mypy==2.4.1
|
||||||
pre-commit==4.7.0
|
pre-commit==4.7.0
|
||||||
pylint==4.1.3
|
pylint==4.1.4
|
||||||
pytest==9.2.0
|
pytest==9.2.0
|
||||||
pytest-cov==7.1.0
|
pytest-cov==7.1.0
|
||||||
ruff==0.17.4
|
ruff==0.17.5
|
||||||
|
|||||||
@ -101,13 +101,15 @@ repos:
|
|||||||
- --disable-error-code=list-item
|
- --disable-error-code=list-item
|
||||||
|
|
||||||
- repo: https://github.com/pylint-dev/pylint
|
- repo: https://github.com/pylint-dev/pylint
|
||||||
rev: v4.0.8
|
rev: v4.1.4
|
||||||
hooks:
|
hooks:
|
||||||
- id: pylint
|
- id: pylint
|
||||||
args:
|
args:
|
||||||
- --rcfile=freedays/pyproject.toml
|
- --rcfile=freedays/pyproject.toml
|
||||||
- --fail-under=10
|
- --fail-under=10
|
||||||
- --jobs=4
|
# One process: with --jobs>1 pylint pickles its AST via dill, which
|
||||||
|
# dies on Python 3.15 (code objects lost co_lnotab), 2026-11-16.
|
||||||
|
- --jobs=1
|
||||||
additional_dependencies:
|
additional_dependencies:
|
||||||
- pytest
|
- pytest
|
||||||
# Kept in step with pyproject.toml, so pylint resolves the crdt_sync
|
# Kept in step with pyproject.toml, so pylint resolves the crdt_sync
|
||||||
|
|||||||
@ -2,9 +2,9 @@
|
|||||||
# floor is satisfied by anything newer, so it tells a checker nothing
|
# floor is satisfied by anything newer, so it tells a checker nothing
|
||||||
# about whether this repo is actually current.
|
# about whether this repo is actually current.
|
||||||
bandit[toml]==1.9.4
|
bandit[toml]==1.9.4
|
||||||
mypy==2.4.0
|
mypy==2.4.1
|
||||||
pre-commit==4.7.0
|
pre-commit==4.7.0
|
||||||
pylint==4.1.3
|
pylint==4.1.4
|
||||||
pytest==9.1.1
|
pytest==9.2.0
|
||||||
pytest-cov==7.1.0
|
pytest-cov==7.1.0
|
||||||
ruff==0.17.2
|
ruff==0.17.5
|
||||||
|
|||||||
131
game_recording/.pre-commit-config.yaml
Normal file
131
game_recording/.pre-commit-config.yaml
Normal file
@ -0,0 +1,131 @@
|
|||||||
|
# Pre-commit Configuration for game_recording
|
||||||
|
# Install: pre-commit install && pre-commit install --hook-type pre-push
|
||||||
|
# Run: pre-commit run --all-files
|
||||||
|
# Update: pre-commit autoupdate
|
||||||
|
|
||||||
|
# NOTE: this subproject lives inside the ~/src/utils monorepo, whose git root is
|
||||||
|
# one level up. pre-commit always runs hooks from the git root, so every path
|
||||||
|
# below is written relative to THAT, not to this directory, and the top-level
|
||||||
|
# `files` key keeps these hooks off the sibling subprojects. CI invokes this
|
||||||
|
# config exactly the same way:
|
||||||
|
# pre-commit run --config game_recording/.pre-commit-config.yaml --all-files
|
||||||
|
files: ^game_recording/
|
||||||
|
|
||||||
|
default_language_version:
|
||||||
|
python: python3
|
||||||
|
default_stages: [pre-commit]
|
||||||
|
fail_fast: false
|
||||||
|
|
||||||
|
repos:
|
||||||
|
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||||
|
rev: v4.6.0
|
||||||
|
hooks:
|
||||||
|
- id: trailing-whitespace
|
||||||
|
args: [--markdown-linebreak-ext=md]
|
||||||
|
- id: end-of-file-fixer
|
||||||
|
- id: check-yaml
|
||||||
|
- id: check-json
|
||||||
|
- id: check-toml
|
||||||
|
- id: check-added-large-files
|
||||||
|
args: [--maxkb=2000]
|
||||||
|
- id: check-merge-conflict
|
||||||
|
- id: detect-private-key
|
||||||
|
- id: debug-statements
|
||||||
|
- id: name-tests-test
|
||||||
|
args: [--pytest-test-first]
|
||||||
|
- id: check-ast
|
||||||
|
- id: mixed-line-ending
|
||||||
|
args: [--fix=lf]
|
||||||
|
- id: requirements-txt-fixer
|
||||||
|
|
||||||
|
- repo: local
|
||||||
|
hooks:
|
||||||
|
- id: file-length-cap
|
||||||
|
name: file length <= 250 lines
|
||||||
|
entry: bash scripts/check_file_length.sh
|
||||||
|
language: system
|
||||||
|
pass_filenames: true
|
||||||
|
- id: subproject-scope
|
||||||
|
name: subproject scope regex still matches
|
||||||
|
entry: scripts/check_subproject_scope.sh game_recording
|
||||||
|
language: script
|
||||||
|
# always_run so the top-level `files` filter cannot skip the one hook
|
||||||
|
# whose job is to notice that filter has stopped matching anything.
|
||||||
|
always_run: true
|
||||||
|
pass_filenames: false
|
||||||
|
- id: no-noqa
|
||||||
|
name: Block noqa comments
|
||||||
|
entry: '(?i)#\s*(noqa|type:\s*ignore)'
|
||||||
|
language: pygrep
|
||||||
|
types: [python]
|
||||||
|
- id: no-ruff-noqa
|
||||||
|
name: Block ruff noqa file-level comments
|
||||||
|
entry: '(?i)#\s*ruff:\s*noqa'
|
||||||
|
language: pygrep
|
||||||
|
types: [python]
|
||||||
|
|
||||||
|
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||||
|
rev: v0.17.2
|
||||||
|
hooks:
|
||||||
|
- id: ruff
|
||||||
|
args: [--fix, --unsafe-fixes, --exit-non-zero-on-fix, --show-fixes]
|
||||||
|
types_or: [python, pyi]
|
||||||
|
- id: ruff-format
|
||||||
|
types_or: [python, pyi]
|
||||||
|
|
||||||
|
- repo: https://github.com/pre-commit/mirrors-mypy
|
||||||
|
rev: v1.13.0
|
||||||
|
hooks:
|
||||||
|
- id: mypy
|
||||||
|
# Strict mode from the package's own pyproject, which pre-commit would
|
||||||
|
# not find from the git root.
|
||||||
|
args:
|
||||||
|
- --config-file=game_recording/pyproject.toml
|
||||||
|
- --no-error-summary
|
||||||
|
# The tests import pytest: without it every fixture type is Any.
|
||||||
|
additional_dependencies:
|
||||||
|
- pytest==9.2.0
|
||||||
|
|
||||||
|
- repo: https://github.com/pylint-dev/pylint
|
||||||
|
rev: v4.1.4
|
||||||
|
hooks:
|
||||||
|
- id: pylint
|
||||||
|
args:
|
||||||
|
- --rcfile=game_recording/pyproject.toml
|
||||||
|
- --fail-under=10
|
||||||
|
# One process: with --jobs>1 pylint pickles its AST via dill, which
|
||||||
|
# dies on Python 3.15 (code objects lost co_lnotab), 2026-11-16.
|
||||||
|
- --jobs=1
|
||||||
|
additional_dependencies:
|
||||||
|
- pytest
|
||||||
|
|
||||||
|
- repo: https://github.com/PyCQA/bandit
|
||||||
|
rev: 1.9.4
|
||||||
|
hooks:
|
||||||
|
- id: bandit
|
||||||
|
args:
|
||||||
|
- -c
|
||||||
|
- game_recording/pyproject.toml
|
||||||
|
- --severity-level=high
|
||||||
|
- --confidence-level=medium
|
||||||
|
- --skip=B113
|
||||||
|
additional_dependencies: ["bandit[toml]"]
|
||||||
|
exclude: ^(game_recording/game_recording/tests/|.*test.*\.py$)
|
||||||
|
|
||||||
|
- repo: local
|
||||||
|
hooks:
|
||||||
|
- id: pytest-coverage
|
||||||
|
name: pytest with coverage enforcement
|
||||||
|
entry: scripts/run_subproject_tests.sh game_recording --cov=game_recording
|
||||||
|
language: script
|
||||||
|
types: [python]
|
||||||
|
pass_filenames: false
|
||||||
|
require_serial: true
|
||||||
|
stages: [pre-push]
|
||||||
|
|
||||||
|
- repo: https://github.com/codespell-project/codespell
|
||||||
|
rev: v2.3.0
|
||||||
|
hooks:
|
||||||
|
- id: codespell
|
||||||
|
args:
|
||||||
|
- --skip=*.json,*.lock,.git,__pycache__,.venv
|
||||||
91
game_recording/README.md
Normal file
91
game_recording/README.md
Normal file
@ -0,0 +1,91 @@
|
|||||||
|
# game_recording
|
||||||
|
|
||||||
|
Session recorder for a game, as a package (import name `game_recording`, not
|
||||||
|
published to PyPI, stdlib only). It needs Python 3.14 or newer
|
||||||
|
(`requires-python` in `pyproject.toml`). It records a person's own dev play from
|
||||||
|
outside the game (so the game's frame time stays untouched) and stamps the
|
||||||
|
game's telemetry moments onto the video as events and MKV chapters.
|
||||||
|
|
||||||
|
- Starts the game as a child process, finds its X11 window by pid (`xdotool`),
|
||||||
|
records it with `gpu-screen-recorder` (else `ffmpeg` x11grab) plus the audio
|
||||||
|
monitor, and stops the recorder with SIGINT when the game exits.
|
||||||
|
- A window that goes away and returns (an i3 workspace switch) starts a new
|
||||||
|
part file; every part sits on one timeline.
|
||||||
|
- `finalize` writes `<session>.events.json` next to the video and remuxes
|
||||||
|
chapters in without re-encoding. `latest`, `list` and `open N` show moments
|
||||||
|
and open the video in `mpv` three seconds before one.
|
||||||
|
- Recording trouble never changes the game's exit code or stops the game.
|
||||||
|
- Bots, tests, headless and muted runs are never recorded.
|
||||||
|
|
||||||
|
Needs `ffmpeg`, `ffprobe`, `xdotool` and, optionally, `gpu-screen-recorder`.
|
||||||
|
|
||||||
|
Consume via:
|
||||||
|
```
|
||||||
|
game_recording @ git+https://github.com/kuhyx/utils@game-recording-v0.1.0#subdirectory=game_recording
|
||||||
|
```
|
||||||
|
|
||||||
|
## Configure it for a game
|
||||||
|
|
||||||
|
The package knows no game. One `Config` carries everything game-specific; the
|
||||||
|
game's own entry script (a few lines) builds it and calls `cli.main`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from game_recording import Config, MomentMap, cli
|
||||||
|
from game_recording.config import COMMON_DIRECT
|
||||||
|
|
||||||
|
CONFIG = Config(
|
||||||
|
binaries_dir="data/my-game_binaries", # under $HOME; feedback/ lives inside
|
||||||
|
env_prefix="MYGAME", # MYGAME_NO_RECORD, MYGAME_FEEDBACK_DIR, ...
|
||||||
|
moments=MomentMap(
|
||||||
|
direct={**COMMON_DIRECT, "buy": ("item", "cost")},
|
||||||
|
passthrough_prefixes=("sim_", "milestone"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(cli.main(sys.argv[1:], CONFIG))
|
||||||
|
```
|
||||||
|
|
||||||
|
| Field | Meaning |
|
||||||
|
| --- | --- |
|
||||||
|
| `Config.binaries_dir` | The game's binaries folder, relative to `$HOME`. Default feedback dir: `<binaries_dir>/feedback`; recordings go in its `recordings/`. |
|
||||||
|
| `Config.env_prefix` | Variables derive from it: `<P>_NO_RECORD` (`1` = never record), `<P>_FEEDBACK_DIR` (any value = never record), `<P>_BINARIES` (binaries folder override), `<P>_RECORDER_BACKEND` (`auto`, `gsr`, `x11grab`), `<P>_RECORDER_NICE` (default 10). |
|
||||||
|
| `Config.binaries_env` | Overrides the `<P>_BINARIES` variable name. |
|
||||||
|
| `Config.extra_blocking_flags` | More environment flags that switch recording off at `1`. |
|
||||||
|
| `Config.bot_args` | Game args that mark a bot or test run (default `--autodrive`, `--result-file=`, `--expect-window=`, `--screenshot-dir=`, `--save-dir=`). |
|
||||||
|
| `MomentMap.direct` | Event name to the fields kept; one telemetry line is one moment. Default `COMMON_DIRECT`. |
|
||||||
|
| `MomentMap.passthrough_prefixes` | Events starting with these are moments as they are. |
|
||||||
|
| `MomentMap.game_end_fields`, `error_kinds`, `hitch_merge_s` | Fields of a `game_end` moment, the `engine_error` kinds that count, and the merge window of a hitch burst. |
|
||||||
|
| `MomentMap.classifiers` | Extra per-line rules `(row) -> moment or None`, tried first. Build moments with `moments.moment(row, kind, label, **extra)`. |
|
||||||
|
| `MomentMap.session_rules` | Extra rules `(rows) -> moments` for moments that need several lines (a stall, a repeated failure). |
|
||||||
|
|
||||||
|
## Contract with the game
|
||||||
|
|
||||||
|
- The game is started with `--session-id=<id>` and `--feedback-dir=<dir>`
|
||||||
|
appended to its user args (after `--`); a recorded run needs `--dev`.
|
||||||
|
- It writes `<feedback-dir>/feedback.jsonl`, one JSON object per line with
|
||||||
|
`session`, `event`, `seq` and `ms` (its own clock). One `recording_sync`
|
||||||
|
line (`ms` plus `unix` or `unix_us`) pins that clock to unix time.
|
||||||
|
- Output layout: `<feedback-dir>/recordings/<session>.mkv` (`.partN.mkv` for
|
||||||
|
later parts), `.rec.json`, `.events.json`, `.ffmpeg.log`.
|
||||||
|
|
||||||
|
## CLI
|
||||||
|
|
||||||
|
```
|
||||||
|
wrap [--session ID] [--force] [--audio default|lavfi|SRC] [--fps N] [--max-seconds S] -- <game command>
|
||||||
|
finalize <session>.rec.json
|
||||||
|
latest | list [--dir D] [--session ID]
|
||||||
|
open [N] [--dir D] [--session ID] [--dry-run]
|
||||||
|
```
|
||||||
|
|
||||||
|
## Develop
|
||||||
|
|
||||||
|
```
|
||||||
|
pip install -r requirements.txt
|
||||||
|
python -m pytest --cov=game_recording # 100 % branch coverage required
|
||||||
|
pre-commit run --config game_recording/.pre-commit-config.yaml --all-files # from the utils root
|
||||||
|
```
|
||||||
|
|
||||||
|
Version 0.1.0; the tag is `game-recording-v0.1.0`.
|
||||||
11
game_recording/game_recording/__init__.py
Normal file
11
game_recording/game_recording/__init__.py
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""Session recorder for a game: records a dev run beside it, stamps telemetry moments on the video.
|
||||||
|
|
||||||
|
A game configures it with one `Config` (names, blockers, telemetry vocabulary)
|
||||||
|
and calls `game_recording.cli.main`. See the package README for the whole surface.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from game_recording.config import Config, MomentMap
|
||||||
|
|
||||||
|
__version__ = "0.1.0"
|
||||||
|
__all__ = ["Config", "MomentMap", "__version__"]
|
||||||
95
game_recording/game_recording/cli.py
Normal file
95
game_recording/game_recording/cli.py
Normal file
@ -0,0 +1,95 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""Session recording CLI; a game's own entry script calls `main(argv, config)`.
|
||||||
|
|
||||||
|
wrap [--session ID] [--force] [--audio SRC] [--fps N] [--max-seconds S] -- <game command>
|
||||||
|
finalize <rec.json> rebuild events.json + chapters
|
||||||
|
latest|list [--dir D] moments of the newest recording / all recordings
|
||||||
|
open [N] [--session ID] [--dir D] [--dry-run]
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from game_recording import finalize, library, supervise
|
||||||
|
from game_recording.options import DEFAULT_FPS, RunOptions
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
from game_recording.config import Config
|
||||||
|
from game_recording.library import Doc
|
||||||
|
|
||||||
|
|
||||||
|
def default_dir(config: Config) -> Path:
|
||||||
|
"""The recordings folder of the game's default feedback dir."""
|
||||||
|
return supervise.feedback_dir([], os.environ, config) / "recordings"
|
||||||
|
|
||||||
|
|
||||||
|
def pick(rec_dir: Path, session: str) -> Doc:
|
||||||
|
"""The newest recording (of the session whose id starts with `session`, when given)."""
|
||||||
|
found = library.sessions(rec_dir)
|
||||||
|
if session:
|
||||||
|
found = [p for p in found if p.name.startswith(session)]
|
||||||
|
if not found:
|
||||||
|
msg = f"no recordings in {rec_dir}"
|
||||||
|
raise SystemExit(msg)
|
||||||
|
return library.load(found[0])
|
||||||
|
|
||||||
|
|
||||||
|
def parser() -> argparse.ArgumentParser:
|
||||||
|
"""The argument parser of every subcommand."""
|
||||||
|
top = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||||
|
sub = top.add_subparsers(dest="cmd", required=True)
|
||||||
|
wrap = sub.add_parser("wrap")
|
||||||
|
wrap.add_argument("--session", default="")
|
||||||
|
wrap.add_argument("--force", action="store_true", help="record bot/test runs too (tests only)")
|
||||||
|
wrap.add_argument("--audio", default="default", help="default|lavfi|<pulse source>")
|
||||||
|
wrap.add_argument("--fps", type=int, default=DEFAULT_FPS)
|
||||||
|
wrap.add_argument("--max-seconds", type=float, default=0.0)
|
||||||
|
wrap.add_argument("command", nargs=argparse.REMAINDER)
|
||||||
|
fin = sub.add_parser("finalize")
|
||||||
|
fin.add_argument("meta")
|
||||||
|
for name in ("latest", "list", "open"):
|
||||||
|
p = sub.add_parser(name)
|
||||||
|
p.add_argument("--dir", default="")
|
||||||
|
p.add_argument("--session", default="")
|
||||||
|
if name == "open":
|
||||||
|
p.add_argument("n", nargs="?", type=int)
|
||||||
|
p.add_argument("--dry-run", action="store_true")
|
||||||
|
return top
|
||||||
|
|
||||||
|
|
||||||
|
def _wrap(args: argparse.Namespace, config: Config) -> int:
|
||||||
|
command = args.command[1:] if args.command[:1] == ["--"] else args.command
|
||||||
|
options = RunOptions(
|
||||||
|
force=args.force, session=args.session, audio=args.audio, fps=args.fps, max_seconds=args.max_seconds
|
||||||
|
)
|
||||||
|
return supervise.run(command, config, options)
|
||||||
|
|
||||||
|
|
||||||
|
def _show(args: argparse.Namespace, config: Config) -> int:
|
||||||
|
rec_dir = Path(args.dir) if args.dir else default_dir(config)
|
||||||
|
if args.cmd == "list":
|
||||||
|
sys.stdout.write(library.listing(rec_dir) + "\n")
|
||||||
|
elif args.cmd == "latest":
|
||||||
|
sys.stdout.write(library.table(pick(rec_dir, args.session)) + "\n")
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
return library.open_moment(pick(rec_dir, args.session), rec_dir, args.n, dry_run=args.dry_run)
|
||||||
|
except IndexError as err:
|
||||||
|
raise SystemExit(str(err)) from err
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: Sequence[str], config: Config) -> int:
|
||||||
|
"""Runs one subcommand for the game described by `config`; returns the exit code."""
|
||||||
|
args = parser().parse_args(argv)
|
||||||
|
if args.cmd == "wrap":
|
||||||
|
return _wrap(args, config)
|
||||||
|
if args.cmd == "finalize":
|
||||||
|
finalize.finalize(Path(args.meta), config.moments)
|
||||||
|
return 0
|
||||||
|
return _show(args, config)
|
||||||
102
game_recording/game_recording/config.py
Normal file
102
game_recording/game_recording/config.py
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""What a game tells the recorder: its names, its blockers, its telemetry vocabulary.
|
||||||
|
|
||||||
|
The package knows nothing about any one game. A game builds one `Config` and
|
||||||
|
hands it to `game_recording.cli.main` (see the README for the whole surface).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Callable, Mapping
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from types import MappingProxyType
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
type Row = dict[str, Any]
|
||||||
|
"""One telemetry line, as the game wrote it."""
|
||||||
|
type Moment = dict[str, Any]
|
||||||
|
"""One timestamped moment built from telemetry."""
|
||||||
|
type Classifier = Callable[[Row], Moment | None]
|
||||||
|
"""Turns one telemetry line into a moment, or None when it is not one."""
|
||||||
|
type SessionRule = Callable[[list[Row]], list[Moment]]
|
||||||
|
"""Finds the moments that need several telemetry lines."""
|
||||||
|
|
||||||
|
# Entries any dev telemetry has: a moment as they are, with the fields worth keeping.
|
||||||
|
COMMON_DIRECT: Mapping[str, tuple[str, ...]] = MappingProxyType(
|
||||||
|
{
|
||||||
|
"session_start": (),
|
||||||
|
"hub_open": (),
|
||||||
|
"pause_open": (),
|
||||||
|
"pause_close": ("paused_s",),
|
||||||
|
"quit": ("reason",),
|
||||||
|
"session_end": ("reason", "elapsed_s"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
# Game args that only a bot or a test run carries.
|
||||||
|
BOT_ARGS = (
|
||||||
|
"--autodrive",
|
||||||
|
"--result-file=",
|
||||||
|
"--expect-window=",
|
||||||
|
"--screenshot-dir=",
|
||||||
|
"--save-dir=",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class MomentMap:
|
||||||
|
"""Which telemetry entries are moments worth a timestamp.
|
||||||
|
|
||||||
|
Attributes:
|
||||||
|
direct: event name -> the fields kept; one entry is one moment.
|
||||||
|
passthrough_prefixes: events starting with these are moments as they are.
|
||||||
|
game_end_fields: the fields of a `game_end` moment.
|
||||||
|
error_kinds: `engine_error` kinds that are a moment (warnings are noise).
|
||||||
|
hitch_merge_s: `hitch` entries closer than this are one moment.
|
||||||
|
classifiers: extra per-entry rules, tried before the built-in ones.
|
||||||
|
session_rules: extra rules over the whole session, added to the hitch burst.
|
||||||
|
"""
|
||||||
|
|
||||||
|
direct: Mapping[str, tuple[str, ...]] = COMMON_DIRECT
|
||||||
|
passthrough_prefixes: tuple[str, ...] = ()
|
||||||
|
game_end_fields: tuple[str, ...] = ("outcome", "elapsed_s")
|
||||||
|
error_kinds: frozenset[str] = frozenset({"error", "script_error", "shader_error"})
|
||||||
|
hitch_merge_s: float = 2.0
|
||||||
|
classifiers: tuple[Classifier, ...] = ()
|
||||||
|
session_rules: tuple[SessionRule, ...] = ()
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Config:
|
||||||
|
"""One game's recorder settings.
|
||||||
|
|
||||||
|
Attributes:
|
||||||
|
binaries_dir: the game's binaries folder, relative to $HOME; its
|
||||||
|
`feedback/` folder holds the telemetry and the recordings.
|
||||||
|
env_prefix: prefix of the game's environment variables, e.g. `GAME` for
|
||||||
|
`GAME_NO_RECORD`, `GAME_FEEDBACK_DIR`, `GAME_RECORDER_BACKEND`,
|
||||||
|
`GAME_RECORDER_NICE` and `GAME_BINARIES`.
|
||||||
|
moments: the telemetry-to-moment map.
|
||||||
|
bot_args: game args that mark a bot or test run (never recorded).
|
||||||
|
extra_blocking_flags: more env flags that switch recording off at "1".
|
||||||
|
binaries_env: overrides the `<prefix>_BINARIES` variable name.
|
||||||
|
"""
|
||||||
|
|
||||||
|
binaries_dir: str
|
||||||
|
env_prefix: str
|
||||||
|
moments: MomentMap = field(default_factory=MomentMap)
|
||||||
|
bot_args: tuple[str, ...] = BOT_ARGS
|
||||||
|
extra_blocking_flags: tuple[str, ...] = ()
|
||||||
|
binaries_env: str = ""
|
||||||
|
|
||||||
|
def env_name(self, suffix: str) -> str:
|
||||||
|
"""The game's environment variable `<prefix>_<suffix>`."""
|
||||||
|
return f"{self.env_prefix}_{suffix}"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def blocking_flags(self) -> tuple[str, ...]:
|
||||||
|
"""Env flags that count only as "1" and switch recording off."""
|
||||||
|
return (self.env_name("NO_RECORD"), *self.extra_blocking_flags)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def binaries_var(self) -> str:
|
||||||
|
"""The variable that names the binaries folder."""
|
||||||
|
return self.binaries_env or self.env_name("BINARIES")
|
||||||
124
game_recording/game_recording/encoder.py
Normal file
124
game_recording/game_recording/encoder.py
Normal file
@ -0,0 +1,124 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""The ffmpeg command line of a session recording.
|
||||||
|
|
||||||
|
External recorder, so the game's frame time is untouched: x11grab of the game
|
||||||
|
window, PulseAudio/PipeWire monitor audio, hardware encode. Godot's MovieWriter
|
||||||
|
is not an option: it forces fixed-step, non-realtime playback.
|
||||||
|
|
||||||
|
Timestamps: frames are stamped with the wall clock as ffmpeg reads them
|
||||||
|
(-use_wallclock_as_timestamps) and pulse stamps audio with it by default.
|
||||||
|
x11grab hands a frame over 1 to 2 frame periods after the screen had that
|
||||||
|
content (measured at 60 and 120 fps under Xvfb), so the video input is shifted
|
||||||
|
back by the middle of that range (GRAB_LATENCY_FRAMES): a stamp then lies within
|
||||||
|
half a frame of the moment its content was on screen. -copyts keeps
|
||||||
|
those absolute and -output_ts_offset -T0 moves them so the file's timeline
|
||||||
|
starts at T0, a unix time the launcher chose. That makes the offset between the
|
||||||
|
game's telemetry (unix-stamped by recording_sync) and the file exact, with no
|
||||||
|
guess about ffmpeg's start-up latency.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
import subprocess
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Collection
|
||||||
|
|
||||||
|
NVENC = "h264_nvenc"
|
||||||
|
X264 = "libx264"
|
||||||
|
NVENC_P7_MAX_PIXELS = 2560 * 1440
|
||||||
|
# Measured: x11grab frames are stamped 1..2 frame periods after their content.
|
||||||
|
GRAB_LATENCY_FRAMES = 1.5
|
||||||
|
DEFAULT_MONITOR = "@DEFAULT_MONITOR@"
|
||||||
|
# A silent source for tests only: stamped with the wall clock like pulse is.
|
||||||
|
LAVFI_AUDIO = "anullsrc=r=48000:cl=stereo"
|
||||||
|
LAVFI_STAMP = "asetpts='RTCTIME/(1000000*TB)'"
|
||||||
|
|
||||||
|
|
||||||
|
class NoEncoderError(Exception):
|
||||||
|
"""Neither NVENC nor libx264 can encode here."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Spec:
|
||||||
|
"""What one recorder part needs to know."""
|
||||||
|
|
||||||
|
window_id: int
|
||||||
|
fps: int
|
||||||
|
t0_unix: float
|
||||||
|
out: str
|
||||||
|
audio: str = "default" # "default" = monitor of the default sink; "lavfi" = test silence; else a pulse source
|
||||||
|
display: str = ":0"
|
||||||
|
width: int = 0 # window size; an odd side is cropped to even (h264 yuv420 needs it)
|
||||||
|
height: int = 0
|
||||||
|
|
||||||
|
|
||||||
|
def pick(usable: Collection[str]) -> str:
|
||||||
|
"""NVENC when it works (the RTX 3090 encodes without touching the game's frame time), else x264."""
|
||||||
|
for name in (NVENC, X264):
|
||||||
|
if name in usable:
|
||||||
|
return name
|
||||||
|
msg = "neither h264_nvenc nor libx264 is usable"
|
||||||
|
raise NoEncoderError(msg)
|
||||||
|
|
||||||
|
|
||||||
|
def probe_usable() -> set[str]:
|
||||||
|
"""Encoders that really encode one frame here (listed is not the same as working)."""
|
||||||
|
ok: set[str] = set()
|
||||||
|
for name in (NVENC, X264):
|
||||||
|
cmd = ["ffmpeg", "-v", "error", "-f", "lavfi", "-i", "color=size=256x256:rate=1", "-frames:v", "1"]
|
||||||
|
cmd += ["-c:v", name, "-f", "null", "-"]
|
||||||
|
done = subprocess.run(cmd, capture_output=True, check=False, timeout=20)
|
||||||
|
if not done.returncode:
|
||||||
|
ok.add(name)
|
||||||
|
return ok
|
||||||
|
|
||||||
|
|
||||||
|
def nvenc_preset(width: int, height: int) -> str:
|
||||||
|
"""The NVENC preset: p7 (best quality) while it keeps real time on the RTX 3090.
|
||||||
|
|
||||||
|
Measured 1.7x at 2560x1440, 2.4x at 1920x1200; above 1440p p7 only reaches 0.78x at 4K, p4 does 1.6x.
|
||||||
|
"""
|
||||||
|
return "p7" if width * height <= NVENC_P7_MAX_PIXELS else "p4"
|
||||||
|
|
||||||
|
|
||||||
|
def _video_codec(name: str, width: int = 0, height: int = 0) -> list[str]:
|
||||||
|
if name == NVENC:
|
||||||
|
preset = nvenc_preset(width, height)
|
||||||
|
return ["-c:v", NVENC, "-preset", preset, "-tune", "hq", "-rc", "vbr", "-cq", "17", "-b:v", "0", "-g", "60"]
|
||||||
|
return ["-c:v", X264, "-crf", "16", "-preset", "veryfast", "-pix_fmt", "yuv420p", "-g", "60"]
|
||||||
|
|
||||||
|
|
||||||
|
def _even_crop(spec: Spec) -> list[str]:
|
||||||
|
if spec.width % 2 or spec.height % 2:
|
||||||
|
return ["-vf", "crop=trunc(iw/2)*2:trunc(ih/2)*2"]
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def _audio_input(audio: str) -> tuple[list[str], list[str]]:
|
||||||
|
"""(input args, output filter args) of the audio source."""
|
||||||
|
if audio == "lavfi":
|
||||||
|
return ["-f", "lavfi", "-i", LAVFI_AUDIO], ["-af", LAVFI_STAMP]
|
||||||
|
source = DEFAULT_MONITOR if audio == "default" else audio
|
||||||
|
return ["-thread_queue_size", "1024", "-f", "pulse", "-i", source], []
|
||||||
|
|
||||||
|
|
||||||
|
def command(spec: Spec, codec: str) -> list[str]:
|
||||||
|
"""The ffmpeg argv. SIGINT makes it finalize the file.
|
||||||
|
|
||||||
|
-shortest ends it when x11grab dies (window unmapped, resized or gone), which the launcher
|
||||||
|
takes as the cue for a new part.
|
||||||
|
"""
|
||||||
|
audio_in, audio_filter = _audio_input(spec.audio)
|
||||||
|
return [
|
||||||
|
"ffmpeg", "-hide_banner", "-loglevel", "warning", "-nostdin", "-y",
|
||||||
|
"-thread_queue_size", "1024", "-use_wallclock_as_timestamps", "1",
|
||||||
|
"-itsoffset", f"{-GRAB_LATENCY_FRAMES / spec.fps:.6f}", "-f", "x11grab", "-window_id", f"0x{spec.window_id:x}",
|
||||||
|
"-framerate", str(spec.fps), "-draw_mouse", "0", "-i", spec.display,
|
||||||
|
*audio_in,
|
||||||
|
"-copyts", "-output_ts_offset", f"{-spec.t0_unix:.6f}",
|
||||||
|
*_even_crop(spec),
|
||||||
|
*_video_codec(codec, spec.width, spec.height),
|
||||||
|
"-c:a", "flac", *audio_filter,
|
||||||
|
"-shortest", "-f", "matroska", spec.out,
|
||||||
|
] # fmt: skip
|
||||||
91
game_recording/game_recording/finalize.py
Normal file
91
game_recording/game_recording/finalize.py
Normal file
@ -0,0 +1,91 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""After the game exits: events.json next to the video, chapters remuxed in (no re-encode)."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
|
from game_recording import gsr, timeline
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from game_recording.config import MomentMap
|
||||||
|
|
||||||
|
|
||||||
|
def _ffprobe(*args: str) -> dict[str, Any]:
|
||||||
|
cmd = ["ffprobe", "-v", "error", "-of", "json", *args]
|
||||||
|
done = subprocess.run(cmd, capture_output=True, text=True, check=True, timeout=60)
|
||||||
|
probed: dict[str, Any] = json.loads(done.stdout)
|
||||||
|
return probed
|
||||||
|
|
||||||
|
|
||||||
|
TAIL_S = 5.0 # only the file's last seconds are scanned for its true end
|
||||||
|
|
||||||
|
|
||||||
|
def probe_span(video: Path) -> tuple[float, float]:
|
||||||
|
"""(first timestamp, duration) in seconds on the file's timeline.
|
||||||
|
|
||||||
|
The end is the last packet's end, not the container's Duration (muxers differ on
|
||||||
|
whether that counts from zero or from the first timestamp).
|
||||||
|
"""
|
||||||
|
fmt = _ffprobe("-show_entries", "format=start_time,duration", str(video))["format"]
|
||||||
|
start = float(fmt.get("start_time", 0))
|
||||||
|
scan = ["-show_entries", "packet=pts_time,duration_time", "-of", "json"]
|
||||||
|
if "duration" in fmt: # a finalized file: jump near the end (cues) instead of reading it all
|
||||||
|
scan = ["-read_intervals", f"{max(0.0, float(fmt['duration']) - TAIL_S)}%", *scan]
|
||||||
|
packets = _ffprobe(*scan, str(video))["packets"]
|
||||||
|
end = max(
|
||||||
|
(float(p["pts_time"]) + float(p.get("duration_time", 0)) for p in packets if "pts_time" in p), default=start
|
||||||
|
)
|
||||||
|
return start, max(0.0, end - start)
|
||||||
|
|
||||||
|
|
||||||
|
def embed_chapters(video: Path, ffmetadata: Path) -> None:
|
||||||
|
"""Remux with chapters, streams copied, timestamps kept (-copyts) so t stays valid."""
|
||||||
|
tmp = video.with_suffix(".chapters.mkv")
|
||||||
|
cmd = ["ffmpeg", "-v", "error", "-y", "-copyts", "-i", str(video), "-f", "ffmetadata", "-i", str(ffmetadata)]
|
||||||
|
cmd += ["-map", "0", "-map_metadata", "0", "-map_chapters", "1", "-c", "copy", "-f", "matroska", str(tmp)]
|
||||||
|
subprocess.run(cmd, check=True, timeout=300)
|
||||||
|
tmp.replace(video)
|
||||||
|
|
||||||
|
|
||||||
|
def _part_spans(folder: Path, meta: dict[str, Any]) -> list[dict[str, Any]]:
|
||||||
|
"""Each existing part file with its first timestamp and duration (gsr parts are aligned first)."""
|
||||||
|
names = [n for n in meta.get("parts") or [meta["video"]] if (folder / n).is_file()]
|
||||||
|
for name, first in (meta.get("first_frame_unix") or {}).items(): # gsr parts: a no-op once aligned
|
||||||
|
if name in names:
|
||||||
|
gsr.align(folder / name, first_unix=float(first), t0=float(meta["t0_unix"]))
|
||||||
|
spans = []
|
||||||
|
for name in names:
|
||||||
|
start_s, duration_s = probe_span(folder / name)
|
||||||
|
spans.append({"file": name, "start_s": start_s, "duration_s": duration_s})
|
||||||
|
return spans
|
||||||
|
|
||||||
|
|
||||||
|
def _embed_all_chapters(folder: Path, doc: dict[str, Any], parts: list[dict[str, Any]]) -> None:
|
||||||
|
"""Remuxes each part that has moments inside it with its chapters."""
|
||||||
|
ffmeta = folder / f"{doc['session']}.ffmeta"
|
||||||
|
for part in parts:
|
||||||
|
chapters = timeline.chapters_ffmetadata(doc["events"], part["duration_s"], part["start_s"], file=part["file"])
|
||||||
|
if "[CHAPTER]" in chapters:
|
||||||
|
ffmeta.write_text(chapters, encoding="utf-8")
|
||||||
|
embed_chapters(folder / part["file"], ffmeta)
|
||||||
|
ffmeta.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def finalize(meta_path: Path, moment_map: MomentMap) -> dict[str, Any]:
|
||||||
|
"""Builds <session>.events.json and each part's chapters from <session>.rec.json; returns the document."""
|
||||||
|
meta_path = Path(meta_path)
|
||||||
|
meta = json.loads(meta_path.read_text(encoding="utf-8"))
|
||||||
|
folder = meta_path.parent
|
||||||
|
parts = _part_spans(folder, meta)
|
||||||
|
entries = timeline.load_session(Path(meta["feedback"]), meta["session"])
|
||||||
|
doc = timeline.build_events(
|
||||||
|
entries, session=meta["session"], t0_unix=float(meta["t0_unix"]), parts=parts, moment_map=moment_map
|
||||||
|
)
|
||||||
|
doc["video"]["file"] = parts[0]["file"]
|
||||||
|
doc["video"]["encoder"] = meta.get("encoder", "")
|
||||||
|
_embed_all_chapters(folder, doc, parts)
|
||||||
|
out = folder / f"{meta['session']}.events.json"
|
||||||
|
out.write_text(json.dumps(doc, indent=1) + "\n", encoding="utf-8")
|
||||||
|
return doc
|
||||||
133
game_recording/game_recording/gsr.py
Normal file
133
game_recording/game_recording/gsr.py
Normal file
@ -0,0 +1,133 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""gpu-screen-recorder (gsr): the low-impact recording backend.
|
||||||
|
|
||||||
|
x11grab makes the X server read every frame of the window back from the GPU into
|
||||||
|
system RAM (about 2 GB/s at 4K60), which slows the game. gsr captures the window
|
||||||
|
on the GPU (XComposite) and encodes with NVENC without that read-back; ffmpeg's
|
||||||
|
x11grab (encoder.py) stays as the fallback when gsr is missing or fails at start.
|
||||||
|
|
||||||
|
Timeline: gsr's file starts at 0 with its first frame, and
|
||||||
|
`-write-first-frame-ts yes` writes `<out>.ts` ("monotonic_microsec<TAB>realtime_microsec"
|
||||||
|
header, then one line of values). The realtime column is the unix time of file
|
||||||
|
time 0, less CAPTURE_LATENCY_S (measured): the first part's t0 is that time; a later part is
|
||||||
|
remuxed (streams copied) so it sits on the same timeline.
|
||||||
|
Audio is Opus: gsr 6.1 has FLAC disabled.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
import signal
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
from typing import IO, TYPE_CHECKING
|
||||||
|
|
||||||
|
from game_recording import encoder, procs
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Mapping
|
||||||
|
|
||||||
|
from game_recording.config import Config
|
||||||
|
|
||||||
|
GSR = "gpu-screen-recorder"
|
||||||
|
BACKEND_SUFFIX = "RECORDER_BACKEND" # the game's <prefix>_RECORDER_BACKEND: auto (default) | gsr | x11grab
|
||||||
|
START_WAIT_S = 8.0 # EGL + NVENC init, until the first frame is stamped
|
||||||
|
TS_FIELDS = 2 # monotonic_microsec, realtime_microsec
|
||||||
|
ALIGN_TOLERANCE_S = 0.002 # a part this close to the timeline is not remuxed
|
||||||
|
# gsr writes the first-frame stamp ~87 ms after the screen showed that content
|
||||||
|
# (a sync bench on a real display, 2026-11-11: ten flips 76-98 ms late at 30 fps), so
|
||||||
|
# file time 0 is that much earlier; the median of the measurement, like x11grab's
|
||||||
|
# GRAB_LATENCY_FRAMES.
|
||||||
|
CAPTURE_LATENCY_S = 0.087
|
||||||
|
|
||||||
|
|
||||||
|
def available() -> bool:
|
||||||
|
"""True when gpu-screen-recorder is installed."""
|
||||||
|
return shutil.which(GSR) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def pick_backend(env: Mapping[str, str], audio: str, config: Config, *, have_gsr: bool) -> str:
|
||||||
|
"""Gsr when installed; x11grab when forced, when gsr is missing, or for the silent test source."""
|
||||||
|
if env.get(config.env_name(BACKEND_SUFFIX)) == "x11grab" or audio == "lavfi" or not have_gsr:
|
||||||
|
return "x11grab"
|
||||||
|
return "gsr"
|
||||||
|
|
||||||
|
|
||||||
|
def command(spec: encoder.Spec) -> list[str]:
|
||||||
|
"""The gsr argv. SIGINT makes it stop and finalize the file."""
|
||||||
|
audio = "default_output" if spec.audio == "default" else f"device:{spec.audio}"
|
||||||
|
return [
|
||||||
|
GSR, "-w", str(spec.window_id), "-f", str(spec.fps), "-fm", "cfr", "-k", "h264", "-q", "very_high",
|
||||||
|
"-c", "mkv", "-cursor", "no", "-a", audio, "-ac", "opus", "-write-first-frame-ts", "yes",
|
||||||
|
"-v", "no", "-o", spec.out,
|
||||||
|
] # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
def ts_path(out: str | Path) -> Path:
|
||||||
|
"""The file gsr writes the first-frame stamp to."""
|
||||||
|
return Path(f"{out}.ts")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_first_frame(text: str) -> float | None:
|
||||||
|
"""Unix seconds of the first frame from the .ts file, None until it is completely written."""
|
||||||
|
if not text.endswith("\n"):
|
||||||
|
return None
|
||||||
|
fields = text.splitlines()[-1].split("\t")
|
||||||
|
if len(fields) != TS_FIELDS or not all(f.isdigit() for f in fields):
|
||||||
|
return None
|
||||||
|
return int(fields[1]) / 1_000_000
|
||||||
|
|
||||||
|
|
||||||
|
def _read_first_frame(path: Path) -> float | None:
|
||||||
|
try:
|
||||||
|
return parse_first_frame(path.read_text(encoding="utf-8"))
|
||||||
|
except OSError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def start(
|
||||||
|
spec: encoder.Spec, log: IO[bytes], nice: str, wait_s: float = START_WAIT_S
|
||||||
|
) -> tuple[subprocess.Popen[bytes], float] | None:
|
||||||
|
"""Starts gsr; (process, unix time of its first frame) once it records, None when it failed."""
|
||||||
|
ts = ts_path(spec.out)
|
||||||
|
ts.unlink(missing_ok=True)
|
||||||
|
proc = procs.spawn(procs.niced(nice, command(spec)), log=log, detach=True)
|
||||||
|
deadline = time.monotonic() + wait_s
|
||||||
|
while proc.poll() is None and time.monotonic() < deadline:
|
||||||
|
first = _read_first_frame(ts)
|
||||||
|
if first is not None:
|
||||||
|
return proc, first - CAPTURE_LATENCY_S
|
||||||
|
time.sleep(0.05)
|
||||||
|
if proc.poll() is None:
|
||||||
|
proc.send_signal(signal.SIGKILL)
|
||||||
|
proc.wait()
|
||||||
|
ts.unlink(missing_ok=True)
|
||||||
|
Path(spec.out).unlink(missing_ok=True)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def shift_delta(first_unix: float, t0: float, first_stamp: float) -> float:
|
||||||
|
"""Seconds to add to a part's stamps so its first frame lands at first_unix on the t0 timeline."""
|
||||||
|
return (first_unix - t0) - first_stamp
|
||||||
|
|
||||||
|
|
||||||
|
def shift_command(src: Path, dst: Path, delta: float) -> list[str]:
|
||||||
|
"""The ffmpeg argv that stream-copies `src` to `dst` with every stamp moved by `delta` seconds."""
|
||||||
|
cmd = ["ffmpeg", "-v", "error", "-y", "-copyts", "-i", str(src), "-map", "0"]
|
||||||
|
return [*cmd, "-c", "copy", "-output_ts_offset", f"{delta:.6f}", "-f", "matroska", str(dst)]
|
||||||
|
|
||||||
|
|
||||||
|
def video_start(video: Path) -> float:
|
||||||
|
"""The first video stamp of the file, in seconds."""
|
||||||
|
cmd = ["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=start_time"]
|
||||||
|
done = subprocess.run([*cmd, "-of", "csv=p=0", str(video)], capture_output=True, text=True, check=True, timeout=60)
|
||||||
|
return float(done.stdout.strip())
|
||||||
|
|
||||||
|
|
||||||
|
def align(video: Path, first_unix: float, t0: float) -> None:
|
||||||
|
"""Moves a finished gsr part onto the t0 timeline (stream copy; nothing when it is already there)."""
|
||||||
|
delta = shift_delta(first_unix, t0, video_start(video))
|
||||||
|
if abs(delta) <= ALIGN_TOLERANCE_S:
|
||||||
|
return
|
||||||
|
tmp = video.with_suffix(".shift.mkv")
|
||||||
|
subprocess.run(shift_command(video, tmp, delta), check=True, timeout=600)
|
||||||
|
tmp.replace(video)
|
||||||
93
game_recording/game_recording/library.py
Normal file
93
game_recording/game_recording/library.py
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""Lists recordings and opens one at a moment (the code behind scripts/recordings.sh)."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import shlex
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
|
from game_recording import timeline
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
type Doc = dict[str, Any]
|
||||||
|
LEAD_S = 3.0 # open this long before the moment, so the cause is on screen
|
||||||
|
|
||||||
|
|
||||||
|
def stamp(seconds: float) -> str:
|
||||||
|
"""mm:ss.mmm of a time on the recording's timeline."""
|
||||||
|
sign = "-" if seconds < 0 else ""
|
||||||
|
millis = round(abs(seconds) * 1000)
|
||||||
|
return f"{sign}{millis // 60000:02d}:{millis // 1000 % 60:02d}.{millis % 1000:03d}"
|
||||||
|
|
||||||
|
|
||||||
|
def sessions(rec_dir: Path) -> list[Path]:
|
||||||
|
"""events.json files, newest first."""
|
||||||
|
return sorted(rec_dir.glob("*.events.json"), key=lambda p: p.stat().st_mtime, reverse=True)
|
||||||
|
|
||||||
|
|
||||||
|
def load(path: Path) -> Doc:
|
||||||
|
"""One events.json document."""
|
||||||
|
doc: Doc = json.loads(path.read_text(encoding="utf-8"))
|
||||||
|
return doc
|
||||||
|
|
||||||
|
|
||||||
|
def shown(doc: Doc) -> list[Doc]:
|
||||||
|
"""The moments inside a recording part, in the numbering `open <n>` uses (1-based)."""
|
||||||
|
return [e for e in doc["events"] if timeline.in_recording(e)]
|
||||||
|
|
||||||
|
|
||||||
|
def table(doc: Doc) -> str:
|
||||||
|
"""One recording as text: a header line, notes, then its numbered moments."""
|
||||||
|
video = doc["video"]
|
||||||
|
lines = [f"{doc['session']} {doc.get('tag', '')} {stamp(video['duration_s'])} {video.get('file', '')}"]
|
||||||
|
if len(video.get("parts", [])) > 1:
|
||||||
|
spans = ", ".join(
|
||||||
|
f"{p['file']} {stamp(p['start_s'])}-{stamp(p['start_s'] + p['duration_s'])}" for p in video["parts"]
|
||||||
|
)
|
||||||
|
lines.append(f"note: the window went away; {len(video['parts'])} parts: {spans}")
|
||||||
|
if doc["sync"]["approx"]:
|
||||||
|
lines.append("note: clocks synced from a whole-second wall time (build without recording_sync), +-1 s")
|
||||||
|
for n, event in enumerate(shown(doc), 1):
|
||||||
|
png = f" {event['png']}" if event.get("png") else ""
|
||||||
|
part = f" [{event['file']}]" if event.get("file") and event["file"] != video.get("file") else ""
|
||||||
|
lines.append(f"{n:3d} {stamp(event['t'])} {event['label']}{png}{part}")
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
def listing(rec_dir: Path) -> str:
|
||||||
|
"""One line per recording, newest first."""
|
||||||
|
out = []
|
||||||
|
for path in sessions(rec_dir):
|
||||||
|
doc = load(path)
|
||||||
|
out.append(
|
||||||
|
f"{doc['session']} {stamp(doc['video']['duration_s'])} {len(shown(doc))} moments {doc.get('tag', '')}"
|
||||||
|
)
|
||||||
|
return "\n".join(out)
|
||||||
|
|
||||||
|
|
||||||
|
def open_command(doc: Doc, rec_dir: Path, n: int | None) -> list[str]:
|
||||||
|
"""Mpv argv at moment n (None = from the start). --rebase-start-time=no keeps mpv on the file's own timeline."""
|
||||||
|
parts = doc["video"].get("parts") or [{"file": doc["video"]["file"], "start_s": doc["video"]["start_s"]}]
|
||||||
|
name, first_frame = doc["video"]["file"], parts[0]["start_s"]
|
||||||
|
cmd = ["mpv", "--rebase-start-time=no", "--force-window=yes"]
|
||||||
|
if n is not None:
|
||||||
|
moments = shown(doc)
|
||||||
|
if not 1 <= n <= len(moments):
|
||||||
|
msg = f"no moment {n} (1..{len(moments)})"
|
||||||
|
raise IndexError(msg)
|
||||||
|
name = moments[n - 1].get("file", name)
|
||||||
|
first_frame = next((p["start_s"] for p in parts if p["file"] == name), first_frame)
|
||||||
|
cmd.append(f"--start={max(first_frame, moments[n - 1]['t'] - LEAD_S):.3f}")
|
||||||
|
return [*cmd, str(rec_dir / name)]
|
||||||
|
|
||||||
|
|
||||||
|
def open_moment(doc: Doc, rec_dir: Path, n: int | None, *, dry_run: bool) -> int:
|
||||||
|
"""Plays the recording in mpv at moment n (or prints the command when `dry_run`)."""
|
||||||
|
cmd = open_command(doc, rec_dir, n)
|
||||||
|
if dry_run:
|
||||||
|
sys.stdout.write(shlex.join(cmd) + "\n")
|
||||||
|
return 0
|
||||||
|
return subprocess.call(cmd)
|
||||||
162
game_recording/game_recording/moments.py
Normal file
162
game_recording/game_recording/moments.py
Normal file
@ -0,0 +1,162 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""Which telemetry entries are moments worth a timestamp, and the derived ones.
|
||||||
|
|
||||||
|
Direct moments map one entry to one moment (the game's dev telemetry writes
|
||||||
|
them). Derived moments need several entries: a burst of hitches is one moment.
|
||||||
|
Moments carry `ms` (the entry's game clock); timeline.py turns it into `t`.
|
||||||
|
What counts is the game's `MomentMap` (config.py); this module only applies it.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Callable
|
||||||
|
|
||||||
|
from game_recording.config import Moment, MomentMap, Row
|
||||||
|
|
||||||
|
# Fields every entry carries; never part of a passthrough moment's payload.
|
||||||
|
ENVELOPE = ("session", "time", "frame", "tag", "event", "seq", "ms")
|
||||||
|
ANNOTATION = "annotation"
|
||||||
|
NEVER_MS = -(10**12)
|
||||||
|
|
||||||
|
|
||||||
|
def event_name(row: Row) -> str:
|
||||||
|
"""The entry's event name, "" when it has none."""
|
||||||
|
return str(row.get("event", ""))
|
||||||
|
|
||||||
|
|
||||||
|
def moment(row: Row, kind: str, label: str, **extra: object) -> Moment:
|
||||||
|
"""A moment at the entry's game clock; custom rules build theirs with this."""
|
||||||
|
out: Moment = {
|
||||||
|
"kind": kind,
|
||||||
|
"label": label,
|
||||||
|
"event": event_name(row),
|
||||||
|
"seq": row.get("seq"),
|
||||||
|
"ms": row["ms"],
|
||||||
|
}
|
||||||
|
if row.get("game"):
|
||||||
|
out["game"] = row["game"]
|
||||||
|
out.update(extra)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _keep(row: Row, keys: tuple[str, ...]) -> Row:
|
||||||
|
return {k: row[k] for k in keys if k in row}
|
||||||
|
|
||||||
|
|
||||||
|
def _words(value: object) -> str:
|
||||||
|
"""A field value as label text: a list reads as a,b,c."""
|
||||||
|
if isinstance(value, list):
|
||||||
|
return ",".join(str(v) for v in value)
|
||||||
|
return str(value)
|
||||||
|
|
||||||
|
|
||||||
|
def _direct(row: Row, moment_map: MomentMap) -> Moment | None:
|
||||||
|
name = event_name(row)
|
||||||
|
if name not in moment_map.direct:
|
||||||
|
return None
|
||||||
|
extra = _keep(row, moment_map.direct[name])
|
||||||
|
detail = " ".join(_words(v) for v in extra.values() if v not in ("", None))
|
||||||
|
return moment(
|
||||||
|
row,
|
||||||
|
name,
|
||||||
|
f"{name} {row.get('game', '')} {detail}".replace(" ", " ").strip(),
|
||||||
|
**extra,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _game_end(row: Row, moment_map: MomentMap) -> Moment | None:
|
||||||
|
if event_name(row) != "game_end":
|
||||||
|
return None
|
||||||
|
extra = _keep(row, moment_map.game_end_fields)
|
||||||
|
return moment(row, "game_end", f"game_end {row.get('outcome', '')}".strip(), **extra)
|
||||||
|
|
||||||
|
|
||||||
|
def _annotation(row: Row, _moment_map: MomentMap) -> Moment | None:
|
||||||
|
if event_name(row) != ANNOTATION:
|
||||||
|
return None
|
||||||
|
return moment(
|
||||||
|
row,
|
||||||
|
ANNOTATION,
|
||||||
|
"F12 annotation",
|
||||||
|
png=row.get("image", ""),
|
||||||
|
marks=row.get("marks"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _engine_error(row: Row, moment_map: MomentMap) -> Moment | None:
|
||||||
|
if event_name(row) != "engine_error" or row.get("kind") not in moment_map.error_kinds:
|
||||||
|
return None
|
||||||
|
text = str(row.get("message", ""))[:60]
|
||||||
|
extra = _keep(row, ("message", "file", "line"))
|
||||||
|
return moment(row, "engine_error", f"engine_error {text}", error_kind=row["kind"], **extra)
|
||||||
|
|
||||||
|
|
||||||
|
def _passthrough(row: Row, moment_map: MomentMap) -> Moment | None:
|
||||||
|
name = event_name(row)
|
||||||
|
if not (moment_map.passthrough_prefixes and name.startswith(moment_map.passthrough_prefixes)):
|
||||||
|
return None
|
||||||
|
extra = {k: v for k, v in row.items() if k not in ENVELOPE}
|
||||||
|
return moment(row, name, name, **extra)
|
||||||
|
|
||||||
|
|
||||||
|
_BUILT_IN: tuple[Callable[[Row, MomentMap], Moment | None], ...] = (
|
||||||
|
_direct,
|
||||||
|
_game_end,
|
||||||
|
_annotation,
|
||||||
|
_engine_error,
|
||||||
|
_passthrough,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _one(row: Row, moment_map: MomentMap) -> Moment | None:
|
||||||
|
for classifier in moment_map.classifiers:
|
||||||
|
found = classifier(row)
|
||||||
|
if found is not None:
|
||||||
|
return found
|
||||||
|
for rule in _BUILT_IN:
|
||||||
|
found = rule(row, moment_map)
|
||||||
|
if found is not None:
|
||||||
|
return found
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def classify(rows: list[Row], moment_map: MomentMap) -> list[Moment]:
|
||||||
|
"""The direct moments of a session's entries."""
|
||||||
|
return [m for m in (_one(r, moment_map) for r in rows) if m is not None]
|
||||||
|
|
||||||
|
|
||||||
|
def derive(rows: list[Row], moment_map: MomentMap) -> list[Moment]:
|
||||||
|
"""The moments that need more than one entry."""
|
||||||
|
out = _hitches(rows, moment_map.hitch_merge_s)
|
||||||
|
for session_rule in moment_map.session_rules:
|
||||||
|
out += session_rule(rows)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _hitches(rows: list[Row], merge_s: float) -> list[Moment]:
|
||||||
|
"""A burst of `hitch` entries closer than `merge_s` is one moment."""
|
||||||
|
out: list[Moment] = []
|
||||||
|
last_ms = NEVER_MS
|
||||||
|
for row in rows:
|
||||||
|
if event_name(row) != "hitch":
|
||||||
|
continue
|
||||||
|
dur = row.get("dur_ms", 0)
|
||||||
|
if out and row["ms"] - last_ms <= merge_s * 1000:
|
||||||
|
out[-1]["count"] += 1
|
||||||
|
out[-1]["max_ms"] = max(out[-1]["max_ms"], dur)
|
||||||
|
else:
|
||||||
|
out.append(
|
||||||
|
moment(
|
||||||
|
row,
|
||||||
|
"hitch",
|
||||||
|
"",
|
||||||
|
count=1,
|
||||||
|
max_ms=dur,
|
||||||
|
cause=row.get("cause", ""),
|
||||||
|
derived=True,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
out[-1]["label"] = f"hitch x{out[-1]['count']} max {out[-1]['max_ms']} ms"
|
||||||
|
last_ms = row["ms"]
|
||||||
|
return out
|
||||||
34
game_recording/game_recording/options.py
Normal file
34
game_recording/game_recording/options.py
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""The settings of one recorded run, as plain values."""
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
DEFAULT_FPS = 30
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class RunOptions:
|
||||||
|
"""What the command line asks of `supervise.run`."""
|
||||||
|
|
||||||
|
force: bool = False # record bot and test runs too (tests only)
|
||||||
|
session: str = ""
|
||||||
|
audio: str = "default" # default | lavfi | <pulse source>
|
||||||
|
fps: int = DEFAULT_FPS
|
||||||
|
max_seconds: float = 0.0 # the test flag: stop the game this long after recording began
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class RecorderOptions:
|
||||||
|
"""What the recorder needs to start parts of one session."""
|
||||||
|
|
||||||
|
session: str
|
||||||
|
feedback: Path
|
||||||
|
fps: int
|
||||||
|
audio: str
|
||||||
|
nice: str
|
||||||
|
usable: frozenset[str]
|
||||||
|
backend: str = "x11grab" # gsr or x11grab
|
||||||
75
game_recording/game_recording/policy.py
Normal file
75
game_recording/game_recording/policy.py
Normal file
@ -0,0 +1,75 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""When a run is recorded: a person's own dev play, never bots, tests or headless runs."""
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Mapping, Sequence
|
||||||
|
|
||||||
|
from game_recording.config import Config
|
||||||
|
|
||||||
|
DEV_ARG = "--dev"
|
||||||
|
NO_DEV_ARG = "--no-dev"
|
||||||
|
# (engine flag, the value after it that makes the run headless or muted)
|
||||||
|
ENGINE_BLOCKERS = (("--display-driver", "headless"), ("--audio-driver", "Dummy"))
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Decision:
|
||||||
|
"""Whether to record, and the reason either way."""
|
||||||
|
|
||||||
|
record: bool
|
||||||
|
reason: str
|
||||||
|
|
||||||
|
|
||||||
|
def arg_value(args: Sequence[str], prefix: str) -> str:
|
||||||
|
"""The value of the first `<prefix>value` argument, "" when absent."""
|
||||||
|
for arg in args:
|
||||||
|
if arg.startswith(prefix):
|
||||||
|
return arg[len(prefix) :]
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _engine_blocker(args: Sequence[str]) -> str:
|
||||||
|
"""Why the engine arguments (before `--`) make this a headless or muted run."""
|
||||||
|
engine = list(args[: args.index("--")]) if "--" in args else list(args)
|
||||||
|
if "--headless" in engine:
|
||||||
|
return "--headless"
|
||||||
|
for flag, value in ENGINE_BLOCKERS:
|
||||||
|
if flag in engine and engine[engine.index(flag) + 1 : engine.index(flag) + 2] == [value]:
|
||||||
|
return f"{flag} {value}"
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _env_blocker(env: Mapping[str, str], config: Config) -> str:
|
||||||
|
"""Why the environment opts out: a flag is on only as "1"; a feedback dir is a path, any value counts."""
|
||||||
|
for name in config.blocking_flags:
|
||||||
|
if env.get(name) == "1":
|
||||||
|
return f"{name}=1"
|
||||||
|
path = config.env_name("FEEDBACK_DIR")
|
||||||
|
return f"{path} is set" if env.get(path) else ""
|
||||||
|
|
||||||
|
|
||||||
|
def _args_blocker(args: Sequence[str], config: Config) -> str:
|
||||||
|
"""Why the game's own arguments say this is not dev play."""
|
||||||
|
if NO_DEV_ARG in args or DEV_ARG not in args:
|
||||||
|
return "not a --dev run"
|
||||||
|
for marker in config.bot_args:
|
||||||
|
hit = next((a for a in args if a.startswith(marker)), "")
|
||||||
|
if hit:
|
||||||
|
return f"bot or test run ({hit})"
|
||||||
|
blocker = _engine_blocker(args)
|
||||||
|
return f"headless or muted run ({blocker})" if blocker else ""
|
||||||
|
|
||||||
|
|
||||||
|
def decide(args: Sequence[str], env: Mapping[str, str], config: Config, *, force: bool = False) -> Decision:
|
||||||
|
"""Record only a windowed dev run on a real display; `force` is for tests."""
|
||||||
|
if not env.get("DISPLAY"):
|
||||||
|
return Decision(record=False, reason="no DISPLAY")
|
||||||
|
if force:
|
||||||
|
return Decision(record=True, reason="forced")
|
||||||
|
reason = _env_blocker(env, config) or _args_blocker(args, config)
|
||||||
|
if reason:
|
||||||
|
return Decision(record=False, reason=reason)
|
||||||
|
return Decision(record=True, reason="dev play")
|
||||||
33
game_recording/game_recording/procs.py
Normal file
33
game_recording/game_recording/procs.py
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""Helpers for starting the external programs (ffmpeg, gpu-screen-recorder, xdotool, mpv)."""
|
||||||
|
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Mapping, Sequence
|
||||||
|
from typing import IO
|
||||||
|
|
||||||
|
|
||||||
|
def program(name: str) -> str:
|
||||||
|
"""The full path of an installed program; the bare name when it is not on PATH (the start then fails clearly)."""
|
||||||
|
return shutil.which(name) or name
|
||||||
|
|
||||||
|
|
||||||
|
def niced(nice: str, argv: Sequence[str]) -> list[str]:
|
||||||
|
"""`argv` run under `nice -n <nice>`: when the CPU is contended the game wins, not the recorder."""
|
||||||
|
return [program("nice"), "-n", nice, *argv]
|
||||||
|
|
||||||
|
|
||||||
|
def spawn(
|
||||||
|
argv: Sequence[str],
|
||||||
|
*,
|
||||||
|
env: Mapping[str, str] | None = None,
|
||||||
|
log: IO[bytes] | None = None,
|
||||||
|
detach: bool = False,
|
||||||
|
) -> subprocess.Popen[bytes]:
|
||||||
|
"""Starts a child that outlives this call; `log` takes its output, `detach` gives it its own session."""
|
||||||
|
return subprocess.Popen(
|
||||||
|
list(argv), env=None if env is None else dict(env), stdout=log, stderr=log, start_new_session=detach
|
||||||
|
)
|
||||||
223
game_recording/game_recording/recorder.py
Normal file
223
game_recording/game_recording/recorder.py
Normal file
@ -0,0 +1,223 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""The recorder beside the game: gpu-screen-recorder, or ffmpeg x11grab as the fallback.
|
||||||
|
|
||||||
|
One part file per run of the recorder; every part sits on the same t0 timeline (the
|
||||||
|
unix time of the first part's time 0), see encoder.py (x11grab) and gsr.py.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import signal
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from game_recording import encoder, gsr, procs, window
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from game_recording.options import RecorderOptions
|
||||||
|
|
||||||
|
WINDOW_WAIT_S = 30.0
|
||||||
|
RETURN_WAIT_S = 3600.0 # a window that went away may take a whole break to return
|
||||||
|
MAX_QUICK_DEATHS = 3 # ffmpeg dying right at start this many times in a row: give up
|
||||||
|
RECORDER_NICE = 10
|
||||||
|
STOP_GRACE_S = 20.0
|
||||||
|
SHORT_LIFE_S = 5.0 # a gsr part that ends sooner than this counts against gsr
|
||||||
|
X11GRAB_SETTLE_S = 1.0 # still running after this long = recording
|
||||||
|
|
||||||
|
|
||||||
|
def say(message: str) -> None:
|
||||||
|
"""One status line on stderr."""
|
||||||
|
sys.stderr.write(f"record: {message}\n")
|
||||||
|
sys.stderr.flush()
|
||||||
|
|
||||||
|
|
||||||
|
def stop_recorder(proc: subprocess.Popen[bytes], grace_s: float = STOP_GRACE_S) -> bool:
|
||||||
|
"""SIGINT so the recorder writes the trailer; kill only after the grace. True = it finalized by itself."""
|
||||||
|
if proc.poll() is not None:
|
||||||
|
return True
|
||||||
|
proc.send_signal(signal.SIGINT)
|
||||||
|
try:
|
||||||
|
proc.wait(timeout=grace_s)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
proc.kill()
|
||||||
|
proc.wait()
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def part_file(session: str, number: int) -> str:
|
||||||
|
"""Part 1 is <session>.mkv; each restart (window came back) adds <session>.partN.mkv."""
|
||||||
|
return f"{session}.mkv" if number == 1 else f"{session}.part{number}.mkv"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class GsrState:
|
||||||
|
"""What the recorder remembers about gpu-screen-recorder parts."""
|
||||||
|
|
||||||
|
open_part: tuple[Path, float] | None = None # (file, first-frame unix) of the running part
|
||||||
|
pending: list[tuple[Path, float]] = field(default_factory=list) # ended parts, aligned after the game
|
||||||
|
first_frames: dict[str, float] = field(default_factory=dict) # part file -> unix time of its first frame
|
||||||
|
started: float = 0.0 # monotonic start of the running part
|
||||||
|
short_lives: int = 0
|
||||||
|
|
||||||
|
|
||||||
|
class Recorder:
|
||||||
|
"""The recorder process, restarted when the game's window goes away and returns.
|
||||||
|
|
||||||
|
The window capture ends when the window is unmapped (an i3 workspace switch), resized or
|
||||||
|
replaced. Each run is a part file on the same t0 timeline; the time between
|
||||||
|
parts is simply not in the video (events there are `in_gap`). `backend` is "gsr" or
|
||||||
|
"x11grab"; a gsr that fails to start switches the rest of the session to x11grab.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, game: subprocess.Popen[bytes], paths: dict[str, Path], opts: RecorderOptions) -> None:
|
||||||
|
"""Watches `game`; writes into `paths` (dir, video, events, meta, log)."""
|
||||||
|
self.game, self.paths, self.opts = game, paths, opts
|
||||||
|
self.backend = opts.backend
|
||||||
|
self.proc: subprocess.Popen[bytes] | None = None
|
||||||
|
self.parts: list[str] = []
|
||||||
|
self.t0 = 0.0
|
||||||
|
self.quick_deaths = 0
|
||||||
|
self.off = False
|
||||||
|
self.win: window.Window | None = None # the window the running part records
|
||||||
|
self.gsr = GsrState()
|
||||||
|
|
||||||
|
def _write_meta(self, codec: str, win: window.Window) -> None:
|
||||||
|
meta = {
|
||||||
|
"session": self.opts.session, "t0_unix": self.t0, "video": self.parts[0], "parts": self.parts,
|
||||||
|
"feedback": str(self.opts.feedback / "feedback.jsonl"), "encoder": codec, "backend": self.backend,
|
||||||
|
"first_frame_unix": self.gsr.first_frames, "audio": self.opts.audio, "fps": self.opts.fps,
|
||||||
|
"window": {"id": win.id, "width": win.width, "height": win.height},
|
||||||
|
} # fmt: skip
|
||||||
|
self.paths["meta"].write_text(json.dumps(meta, indent=1) + "\n", encoding="utf-8")
|
||||||
|
|
||||||
|
def _spec(self, win: window.Window, out: Path) -> encoder.Spec:
|
||||||
|
return encoder.Spec(
|
||||||
|
window_id=win.id, fps=self.opts.fps, t0_unix=self.t0, out=str(out),
|
||||||
|
audio=self.opts.audio, display=os.environ["DISPLAY"], width=win.width, height=win.height,
|
||||||
|
) # fmt: skip
|
||||||
|
|
||||||
|
def _start_gsr(self, win: window.Window, name: str, out: Path) -> bool:
|
||||||
|
with self.paths["log"].open("ab") as log:
|
||||||
|
started = gsr.start(self._spec(win, out), log, self.opts.nice)
|
||||||
|
if started is None:
|
||||||
|
say(f"gpu-screen-recorder failed to start, using x11grab; see {self.paths['log']}")
|
||||||
|
self.backend = "x11grab"
|
||||||
|
return False
|
||||||
|
self.proc, first = started
|
||||||
|
if not self.parts:
|
||||||
|
self.t0 = first # the timeline starts at the first frame, exactly (see gsr.py)
|
||||||
|
self.parts.append(name)
|
||||||
|
self.gsr.open_part = (out, first)
|
||||||
|
self.gsr.first_frames[name] = first
|
||||||
|
self.gsr.started = time.monotonic()
|
||||||
|
self._write_meta("gsr-h264", win)
|
||||||
|
say(f"recording {win.width}x{win.height} with gpu-screen-recorder -> {out}")
|
||||||
|
self.quick_deaths = 0
|
||||||
|
return True
|
||||||
|
|
||||||
|
def _start_x11grab(self, win: window.Window, name: str, out: Path) -> None:
|
||||||
|
codec = encoder.pick(self.opts.usable)
|
||||||
|
if not self.parts:
|
||||||
|
self.t0 = time.time() # the files' timeline starts here, exactly (see encoder.py)
|
||||||
|
spec = self._spec(win, out)
|
||||||
|
self.parts.append(name)
|
||||||
|
self._write_meta(codec, win)
|
||||||
|
with self.paths["log"].open("ab") as log:
|
||||||
|
cmd = procs.niced(self.opts.nice, encoder.command(spec, codec))
|
||||||
|
self.proc = procs.spawn(cmd, log=log, detach=True)
|
||||||
|
try:
|
||||||
|
self.proc.wait(timeout=X11GRAB_SETTLE_S)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
say(f"recording {win.width}x{win.height} with {codec} -> {out}")
|
||||||
|
self.quick_deaths = 0
|
||||||
|
return
|
||||||
|
self.quick_deaths += 1
|
||||||
|
self.parts.pop()
|
||||||
|
self.proc = None
|
||||||
|
say(f"ffmpeg died at start, see {self.paths['log']}")
|
||||||
|
self.off = self.quick_deaths >= MAX_QUICK_DEATHS
|
||||||
|
|
||||||
|
def _start_part(self, win: window.Window) -> None:
|
||||||
|
name = part_file(self.opts.session, len(self.parts) + 1)
|
||||||
|
out = self.paths["dir"] / name
|
||||||
|
self.paths["dir"].mkdir(parents=True, exist_ok=True)
|
||||||
|
self.win = win
|
||||||
|
if self.backend == "gsr" and self._start_gsr(win, name, out):
|
||||||
|
return
|
||||||
|
self._start_x11grab(win, name, out)
|
||||||
|
|
||||||
|
def close_part(self) -> None:
|
||||||
|
"""The running gsr part has ended. Aligning it is a remux (disk I/O), so it waits for the game's end."""
|
||||||
|
if self.gsr.open_part is not None:
|
||||||
|
self.gsr.pending.append(self.gsr.open_part)
|
||||||
|
self.gsr.open_part = None
|
||||||
|
|
||||||
|
def _align_pending(self) -> None:
|
||||||
|
"""Moves each ended gsr part onto the t0 timeline (stream copy). Trouble is only reported."""
|
||||||
|
pending, self.gsr.pending = self.gsr.pending, []
|
||||||
|
for video, first in pending:
|
||||||
|
try:
|
||||||
|
gsr.align(video, first_unix=first, t0=self.t0)
|
||||||
|
except (subprocess.SubprocessError, OSError, ValueError) as err:
|
||||||
|
say(f"could not align {video.name} to the timeline: {err}")
|
||||||
|
|
||||||
|
def _count_short_life(self) -> None:
|
||||||
|
"""A gsr that keeps dying soon after it started is replaced by x11grab for the rest of the session."""
|
||||||
|
if self.gsr.open_part is None:
|
||||||
|
return
|
||||||
|
young = time.monotonic() - self.gsr.started < SHORT_LIFE_S
|
||||||
|
self.gsr.short_lives = self.gsr.short_lives + 1 if young else 0
|
||||||
|
if self.gsr.short_lives >= MAX_QUICK_DEATHS:
|
||||||
|
say("gpu-screen-recorder keeps stopping, using x11grab")
|
||||||
|
self.backend = "x11grab"
|
||||||
|
|
||||||
|
def _still_recording(self) -> bool:
|
||||||
|
"""True while the running part is fine; ends a gsr part whose window changed."""
|
||||||
|
if self.proc is None or self.proc.poll() is not None:
|
||||||
|
return False
|
||||||
|
if self.gsr.open_part is None or window.largest(self.game.pid) == self.win:
|
||||||
|
return True
|
||||||
|
# x11grab dies with its window; gsr neither exits nor resumes after an unmap
|
||||||
|
# (an i3 workspace switch), so its part is ended here and the next one waits.
|
||||||
|
stop_recorder(self.proc)
|
||||||
|
return False
|
||||||
|
|
||||||
|
def step(self) -> bool:
|
||||||
|
"""One look at the recorder; True while a part is being recorded."""
|
||||||
|
if self.off:
|
||||||
|
return False
|
||||||
|
if self._still_recording():
|
||||||
|
return True
|
||||||
|
first = not self.parts
|
||||||
|
if self.proc is not None:
|
||||||
|
say("recorder stopped (the window went away); waiting for it to come back")
|
||||||
|
self.proc = None
|
||||||
|
self._count_short_life()
|
||||||
|
self.close_part()
|
||||||
|
win = window.wait_stable(
|
||||||
|
self.game.pid, WINDOW_WAIT_S if first else RETURN_WAIT_S, lambda: self.game.poll() is None
|
||||||
|
)
|
||||||
|
if win is None:
|
||||||
|
if first:
|
||||||
|
say("no game window found, not recording")
|
||||||
|
self.off = True
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
self._start_part(win)
|
||||||
|
except (encoder.NoEncoderError, OSError) as err:
|
||||||
|
say(f"not recording: {err}")
|
||||||
|
self.off = True
|
||||||
|
return self.proc is not None
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
"""Ends the running part (SIGINT, kill after the grace) and aligns the gsr parts."""
|
||||||
|
if self.proc is not None and not stop_recorder(self.proc):
|
||||||
|
say("the recorder ignored SIGINT and was killed; the mkv keeps what was written")
|
||||||
|
self.close_part()
|
||||||
|
self._align_pending()
|
||||||
177
game_recording/game_recording/supervise.py
Normal file
177
game_recording/game_recording/supervise.py
Normal file
@ -0,0 +1,177 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""Runs the game and, for a person's own dev play, an external recorder beside it.
|
||||||
|
|
||||||
|
The game is a child process; its window is found by pid; the recorder
|
||||||
|
(gpu-screen-recorder, else ffmpeg x11grab, with the audio monitor) starts once the
|
||||||
|
window has settled and gets SIGINT when the game exits, so the mkv is finalized.
|
||||||
|
Then finalize.py writes events.json + chapters.
|
||||||
|
Recording trouble never changes the game's exit code or stops the game.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import secrets
|
||||||
|
import signal
|
||||||
|
import subprocess
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from game_recording import encoder, finalize, gsr, policy, procs, timeline
|
||||||
|
from game_recording.options import RecorderOptions, RunOptions
|
||||||
|
from game_recording.recorder import Recorder, say
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Mapping, Sequence
|
||||||
|
from types import FrameType
|
||||||
|
|
||||||
|
from game_recording.config import Config
|
||||||
|
|
||||||
|
SESSION_ARG = "--session-id="
|
||||||
|
FEEDBACK_ARG = "--feedback-dir="
|
||||||
|
POLL_S = 0.5
|
||||||
|
# What finalize can fail with: files, JSON (NoSyncError is a ValueError), a missing key, ffmpeg.
|
||||||
|
# Recording trouble must not fail the play session.
|
||||||
|
FINALIZE_ERRORS = (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError)
|
||||||
|
DEFAULT_NICE = "10"
|
||||||
|
|
||||||
|
|
||||||
|
def session_of(command: Sequence[str]) -> str:
|
||||||
|
"""The session id the command already carries, "" when none."""
|
||||||
|
return policy.arg_value(command, SESSION_ARG)
|
||||||
|
|
||||||
|
|
||||||
|
def with_session(command: Sequence[str], session: str) -> list[str]:
|
||||||
|
"""The command with `--session-id=` among the game's user args (an existing one wins)."""
|
||||||
|
return _with_user_arg(command, SESSION_ARG, session)
|
||||||
|
|
||||||
|
|
||||||
|
def _with_user_arg(command: Sequence[str], prefix: str, value: str) -> list[str]:
|
||||||
|
out = list(command)
|
||||||
|
if policy.arg_value(out, prefix):
|
||||||
|
return out
|
||||||
|
if "--" not in out:
|
||||||
|
out.append("--")
|
||||||
|
return [*out, f"{prefix}{value}"]
|
||||||
|
|
||||||
|
|
||||||
|
def feedback_dir(command: Sequence[str], env: Mapping[str, str], config: Config) -> Path:
|
||||||
|
"""Where the game's telemetry goes: --feedback-dir=, else the binaries folder's feedback/."""
|
||||||
|
forced = policy.arg_value(command, FEEDBACK_ARG)
|
||||||
|
if forced:
|
||||||
|
return Path(forced)
|
||||||
|
binaries = env.get(config.binaries_var)
|
||||||
|
if binaries:
|
||||||
|
return Path(binaries) / "feedback"
|
||||||
|
return Path(env.get("HOME", str(Path.home()))) / config.binaries_dir / "feedback"
|
||||||
|
|
||||||
|
|
||||||
|
def recording_paths(feedback: Path, session: str) -> dict[str, Path]:
|
||||||
|
"""Every file of one recording, by role."""
|
||||||
|
rec = feedback / "recordings"
|
||||||
|
return {
|
||||||
|
"dir": rec,
|
||||||
|
"video": rec / f"{session}.mkv",
|
||||||
|
"events": rec / f"{session}.events.json",
|
||||||
|
"meta": rec / f"{session}.rec.json",
|
||||||
|
"log": rec / f"{session}.ffmpeg.log",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def new_session() -> str:
|
||||||
|
"""A fresh session id: unix time plus four hex digits."""
|
||||||
|
return f"{int(time.time())}-run-{secrets.token_hex(2)}"
|
||||||
|
|
||||||
|
|
||||||
|
def _forward_signals(game: subprocess.Popen[bytes]) -> None:
|
||||||
|
"""The launcher is a thin parent: kill/hangup go to the game; Ctrl-C already reaches it directly."""
|
||||||
|
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
||||||
|
|
||||||
|
def forward(number: int, _frame: FrameType | None) -> None:
|
||||||
|
game.send_signal(number)
|
||||||
|
|
||||||
|
for sig in (signal.SIGTERM, signal.SIGHUP):
|
||||||
|
signal.signal(sig, forward)
|
||||||
|
|
||||||
|
|
||||||
|
def _stop_game(game: subprocess.Popen[bytes]) -> None:
|
||||||
|
if game.poll() is None:
|
||||||
|
game.send_signal(signal.SIGTERM)
|
||||||
|
|
||||||
|
|
||||||
|
def _finish(paths: dict[str, Path], config: Config) -> None:
|
||||||
|
if not paths["meta"].exists():
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
doc = finalize.finalize(paths["meta"], config.moments)
|
||||||
|
shown = sum(1 for e in doc["events"] if timeline.in_recording(e))
|
||||||
|
parts = doc["video"]["parts"]
|
||||||
|
gaps = f", {len(parts)} parts" if len(parts) > 1 else ""
|
||||||
|
say(f"{paths['dir'] / doc['video']['file']} ({doc['video']['duration_s']:.0f} s, {shown} moments{gaps})")
|
||||||
|
except FINALIZE_ERRORS as err:
|
||||||
|
say(f"could not build the timeline: {err}")
|
||||||
|
|
||||||
|
|
||||||
|
def _nice(env: Mapping[str, str], config: Config) -> str:
|
||||||
|
"""The recorder's nice value; `<prefix>_RECORDER_NICE=0` for tests under a CPU cap."""
|
||||||
|
return env.get(config.env_name("RECORDER_NICE"), DEFAULT_NICE)
|
||||||
|
|
||||||
|
|
||||||
|
def _play_unrecorded(command: Sequence[str], env: Mapping[str, str]) -> int:
|
||||||
|
game = procs.spawn(command, env=env)
|
||||||
|
_forward_signals(game)
|
||||||
|
return game.wait()
|
||||||
|
|
||||||
|
|
||||||
|
def _watch(game: subprocess.Popen[bytes], recorder: Recorder, options: RunOptions) -> None:
|
||||||
|
"""Steps the recorder until the game exits."""
|
||||||
|
timer_started = False
|
||||||
|
while game.poll() is None:
|
||||||
|
recording = recorder.step()
|
||||||
|
if options.max_seconds > 0 and not timer_started and (recording or recorder.off):
|
||||||
|
timer_started = True # the test flag: stop the game N s after recording began
|
||||||
|
threading.Timer(options.max_seconds, _stop_game, (game,)).start()
|
||||||
|
time.sleep(POLL_S)
|
||||||
|
|
||||||
|
|
||||||
|
def _play_recorded(command: Sequence[str], env: Mapping[str, str], config: Config, options: RunOptions) -> int:
|
||||||
|
session = session_of(command) or options.session or new_session()
|
||||||
|
fb = feedback_dir(command, env, config)
|
||||||
|
argv = _with_user_arg(with_session(command, session), FEEDBACK_ARG, str(fb))
|
||||||
|
paths = recording_paths(fb, session)
|
||||||
|
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||||
|
usable = pool.submit(encoder.probe_usable) # NVENC init overlaps the game's start
|
||||||
|
game = procs.spawn(argv, env=env)
|
||||||
|
_forward_signals(game)
|
||||||
|
opts = RecorderOptions(
|
||||||
|
session=session,
|
||||||
|
feedback=fb,
|
||||||
|
fps=options.fps,
|
||||||
|
audio=options.audio,
|
||||||
|
nice=_nice(env, config),
|
||||||
|
usable=frozenset(usable.result()),
|
||||||
|
backend=gsr.pick_backend(env, options.audio, config, have_gsr=gsr.available()),
|
||||||
|
)
|
||||||
|
recorder = Recorder(game, paths, opts)
|
||||||
|
_watch(game, recorder, options)
|
||||||
|
code = game.wait()
|
||||||
|
recorder.stop()
|
||||||
|
_finish(paths, config)
|
||||||
|
return code
|
||||||
|
|
||||||
|
|
||||||
|
def run(
|
||||||
|
command: Sequence[str],
|
||||||
|
config: Config,
|
||||||
|
options: RunOptions | None = None,
|
||||||
|
env: Mapping[str, str] | None = None,
|
||||||
|
) -> int:
|
||||||
|
"""Runs `command`; records it when policy allows. Returns the game's exit code."""
|
||||||
|
options = options or RunOptions()
|
||||||
|
env = os.environ if env is None else env
|
||||||
|
decision = policy.decide(command, env, config, force=options.force)
|
||||||
|
if not decision.record:
|
||||||
|
say(f"off ({decision.reason})")
|
||||||
|
return _play_unrecorded(command, env)
|
||||||
|
return _play_recorded(command, env, config, options)
|
||||||
2
game_recording/game_recording/tests/__init__.py
Normal file
2
game_recording/game_recording/tests/__init__.py
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""Tests of game_recording."""
|
||||||
38
game_recording/game_recording/tests/test_derived.py
Normal file
38
game_recording/game_recording/tests/test_derived.py
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""Derived moments: several telemetry entries that are one moment together."""
|
||||||
|
|
||||||
|
from game_recording import moments
|
||||||
|
from game_recording.tests.test_helpers import MOMENT_MAP, entry
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_burst_of_hitches_is_one_moment() -> None:
|
||||||
|
rows = [
|
||||||
|
entry("hitch", 1000, 1, dur_ms=40, cause="load"),
|
||||||
|
entry("hitch", 1500, 2, dur_ms=90),
|
||||||
|
entry("hitch", 3400, 3, dur_ms=55),
|
||||||
|
]
|
||||||
|
found = moments.derive(rows, MOMENT_MAP)
|
||||||
|
assert len(found) == 1
|
||||||
|
assert found[0]["kind"] == "hitch"
|
||||||
|
assert (found[0]["count"], found[0]["max_ms"]) == (3, 90)
|
||||||
|
assert found[0]["label"] == "hitch x3 max 90 ms"
|
||||||
|
assert found[0]["ms"] == 1000, "stamped at the first hitch"
|
||||||
|
assert found[0]["cause"] == "load"
|
||||||
|
assert found[0]["derived"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_hitches_far_apart_are_separate_moments() -> None:
|
||||||
|
gap_ms = int(MOMENT_MAP.hitch_merge_s * 1000) + 1
|
||||||
|
rows = [entry("hitch", 1000, 1, dur_ms=40), entry("hitch", 1000 + gap_ms, 2, dur_ms=20)]
|
||||||
|
found = moments.derive(rows, MOMENT_MAP)
|
||||||
|
assert [m["label"] for m in found] == ["hitch x1 max 40 ms", "hitch x1 max 20 ms"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_hitch_without_a_duration_counts_as_zero() -> None:
|
||||||
|
assert moments.derive([entry("hitch", 1000, 1)], MOMENT_MAP)[0]["max_ms"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_other_entries_derive_nothing() -> None:
|
||||||
|
rows = [entry("game_start", 1000, 1, game="watch"), entry("command", 2000, 2, order="charge")]
|
||||||
|
assert moments.derive(rows, MOMENT_MAP) == []
|
||||||
|
assert moments.derive([], MOMENT_MAP) == []
|
||||||
113
game_recording/game_recording/tests/test_encoder.py
Normal file
113
game_recording/game_recording/tests/test_encoder.py
Normal file
@ -0,0 +1,113 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""The ffmpeg command line: encoder choice, window capture, exact timestamps."""
|
||||||
|
|
||||||
|
from dataclasses import replace
|
||||||
|
from itertools import pairwise
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from game_recording import encoder
|
||||||
|
|
||||||
|
SPEC = encoder.Spec(window_id=0x4200007, fps=60, t0_unix=1_800_000_000.5, out="/o/s.mkv", audio="default")
|
||||||
|
|
||||||
|
|
||||||
|
def _pairs(cmd: list[str]) -> list[tuple[str, str]]:
|
||||||
|
return list(pairwise(cmd))
|
||||||
|
|
||||||
|
|
||||||
|
def test_nvenc_is_preferred_when_it_works() -> None:
|
||||||
|
assert encoder.pick({"h264_nvenc", "libx264"}) == "h264_nvenc"
|
||||||
|
|
||||||
|
|
||||||
|
def test_falls_back_to_x264() -> None:
|
||||||
|
assert encoder.pick(["libx264"]) == "libx264"
|
||||||
|
|
||||||
|
|
||||||
|
def test_nothing_usable_is_an_error() -> None:
|
||||||
|
with pytest.raises(encoder.NoEncoderError):
|
||||||
|
encoder.pick({"mpeg4"})
|
||||||
|
|
||||||
|
|
||||||
|
def test_probe_lists_only_the_encoders_that_encode_a_frame(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
calls: list[list[str]] = []
|
||||||
|
|
||||||
|
def run(cmd: list[str], **_: object) -> subprocess.CompletedProcess[bytes]:
|
||||||
|
calls.append(cmd)
|
||||||
|
return subprocess.CompletedProcess(cmd, 0 if "libx264" in cmd else 1)
|
||||||
|
|
||||||
|
monkeypatch.setattr(subprocess, "run", run)
|
||||||
|
assert encoder.probe_usable() == {"libx264"}
|
||||||
|
assert len(calls) == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_nvenc_is_quality_first() -> None:
|
||||||
|
pairs = _pairs(encoder.command(SPEC, "h264_nvenc"))
|
||||||
|
for pair in (("-preset", "p7"), ("-rc", "vbr"), ("-cq", "17"), ("-b:v", "0")):
|
||||||
|
assert pair in pairs
|
||||||
|
|
||||||
|
|
||||||
|
def test_4k_windows_use_a_faster_nvenc_preset_to_stay_real_time() -> None:
|
||||||
|
big = replace(SPEC, width=3840, height=2160)
|
||||||
|
assert ("-preset", "p4") in _pairs(encoder.command(big, "h264_nvenc"))
|
||||||
|
qhd = replace(SPEC, width=2560, height=1440)
|
||||||
|
assert ("-preset", "p7") in _pairs(encoder.command(qhd, "h264_nvenc"))
|
||||||
|
|
||||||
|
|
||||||
|
def test_x264_fallback_settings() -> None:
|
||||||
|
pairs = _pairs(encoder.command(SPEC, "libx264"))
|
||||||
|
assert ("-crf", "16") in pairs
|
||||||
|
assert ("-preset", "veryfast") in pairs
|
||||||
|
|
||||||
|
|
||||||
|
def test_captures_the_window_by_id_at_the_fps() -> None:
|
||||||
|
cmd = encoder.command(SPEC, "h264_nvenc")
|
||||||
|
assert ("-window_id", "0x4200007") in _pairs(cmd)
|
||||||
|
assert ("-framerate", "60") in _pairs(cmd)
|
||||||
|
assert "x11grab" in cmd
|
||||||
|
|
||||||
|
|
||||||
|
def test_output_is_mkv_and_sits_on_the_launcher_clock() -> None:
|
||||||
|
cmd = encoder.command(SPEC, "h264_nvenc")
|
||||||
|
assert "-copyts" in cmd
|
||||||
|
assert ("-output_ts_offset", "-1800000000.500000") in _pairs(cmd)
|
||||||
|
assert cmd[-1] == "/o/s.mkv"
|
||||||
|
assert ("-f", "matroska") in _pairs(cmd)
|
||||||
|
|
||||||
|
|
||||||
|
def test_video_stamps_are_shifted_back_by_the_grab_latency() -> None:
|
||||||
|
cmd = encoder.command(SPEC, "h264_nvenc")
|
||||||
|
assert ("-itsoffset", "-0.025000") in _pairs(cmd) # 1.5 frames at 60 fps
|
||||||
|
assert cmd.index("-itsoffset") < cmd.index("x11grab"), "an input option of the video input"
|
||||||
|
|
||||||
|
|
||||||
|
def test_ffmpeg_ends_when_the_window_capture_dies() -> None:
|
||||||
|
assert "-shortest" in encoder.command(SPEC, "h264_nvenc")
|
||||||
|
|
||||||
|
|
||||||
|
def test_audio_is_recorded_not_muted() -> None:
|
||||||
|
cmd = encoder.command(SPEC, "h264_nvenc")
|
||||||
|
assert "pulse" in cmd
|
||||||
|
assert ("-c:a", "flac") in _pairs(cmd)
|
||||||
|
assert ("-i", encoder.DEFAULT_MONITOR) in _pairs(cmd)
|
||||||
|
|
||||||
|
|
||||||
|
def test_pulse_source_is_the_given_monitor() -> None:
|
||||||
|
cmd = encoder.command(replace(SPEC, audio="sink.monitor"), "h264_nvenc")
|
||||||
|
assert ("-i", "sink.monitor") in _pairs(cmd)
|
||||||
|
|
||||||
|
|
||||||
|
def test_silent_test_source_rides_the_wall_clock() -> None:
|
||||||
|
cmd = encoder.command(replace(SPEC, audio="lavfi"), "h264_nvenc")
|
||||||
|
assert "lavfi" in cmd
|
||||||
|
assert any("RTCTIME" in part for part in cmd)
|
||||||
|
|
||||||
|
|
||||||
|
def test_odd_window_sizes_are_cropped_to_even() -> None:
|
||||||
|
assert "-vf" in encoder.command(replace(SPEC, width=1281, height=800), "h264_nvenc")
|
||||||
|
assert "-vf" in encoder.command(replace(SPEC, width=1280, height=801), "h264_nvenc")
|
||||||
|
assert "-vf" not in encoder.command(replace(SPEC, width=1280, height=800), "h264_nvenc")
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_resize_scaler_in_the_path() -> None:
|
||||||
|
assert "-vf" not in encoder.command(SPEC, "h264_nvenc")
|
||||||
96
game_recording/game_recording/tests/test_events.py
Normal file
96
game_recording/game_recording/tests/test_events.py
Normal file
@ -0,0 +1,96 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""Which telemetry entries become moments, and what each one keeps."""
|
||||||
|
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from game_recording import moments
|
||||||
|
from game_recording.tests.test_helpers import MOMENT_MAP, entry
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from game_recording.config import Moment, Row
|
||||||
|
|
||||||
|
|
||||||
|
def one(row: Row, kind: str) -> Moment:
|
||||||
|
found = moments.classify([row], MOMENT_MAP)
|
||||||
|
assert [m["kind"] for m in found] == [kind], row
|
||||||
|
return found[0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_session_start_and_hub_are_moments() -> None:
|
||||||
|
one(entry("session_start", 0, 1), "session_start")
|
||||||
|
assert one(entry("hub_open", 50, 2), "hub_open")["label"] == "hub_open"
|
||||||
|
|
||||||
|
|
||||||
|
def test_game_start_keeps_the_whole_loadout() -> None:
|
||||||
|
row = entry("game_start", 9000, 2, game="command", loadout=["double_men", "stew"], cost=6, men=200, seed=7)
|
||||||
|
m = one(row, "game_start")
|
||||||
|
assert m["game"] == "command"
|
||||||
|
assert m["loadout"] == ["double_men", "stew"]
|
||||||
|
assert (m["cost"], m["men"], m["seed"]) == (6, 200, 7)
|
||||||
|
assert m["label"] == "game_start command double_men,stew 6 200 7"
|
||||||
|
assert (m["ms"], m["seq"], m["event"]) == (9000, 2, "game_start")
|
||||||
|
|
||||||
|
|
||||||
|
def test_game_end_names_the_outcome() -> None:
|
||||||
|
m = one(entry("game_end", 9000, 2, outcome="win", elapsed_s=20.5), "game_end")
|
||||||
|
assert m["label"] == "game_end win"
|
||||||
|
assert m["elapsed_s"] == 20.5
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_buy_and_an_order_keep_their_fields() -> None:
|
||||||
|
buy = one(entry("buy", 100, 2, buff="moose", bought=True, cost=3), "buy")
|
||||||
|
assert buy["label"] == "buy moose True 3"
|
||||||
|
order = one(entry("command", 200, 3, order="rally", pos=[120.0, 80.0]), "command")
|
||||||
|
assert order["order"] == "rally"
|
||||||
|
assert order["label"] == "command rally 120.0,80.0"
|
||||||
|
|
||||||
|
|
||||||
|
def test_pause_lab_reset_quit_and_session_end() -> None:
|
||||||
|
one(entry("pause_open", 9000, 2), "pause_open")
|
||||||
|
assert one(entry("pause_close", 9000, 2, paused_s=3.0), "pause_close")["paused_s"] == 3.0
|
||||||
|
lab = one(entry("lab_result", 9000, 2, wins=12, runs=30, mean_seconds=19.5), "lab_result")
|
||||||
|
assert lab["label"] == "lab_result 12 30 19.5"
|
||||||
|
assert one(entry("reset_progress", 9000, 2, files=1), "reset_progress")["files"] == 1
|
||||||
|
assert one(entry("quit", 9000, 2, reason="menu"), "quit")["reason"] == "menu"
|
||||||
|
end = one(entry("session_end", 9000, 2, reason="exit", elapsed_s=120.0), "session_end")
|
||||||
|
assert end["label"] == "session_end exit 120.0"
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_annotation_carries_its_png_and_mark_count() -> None:
|
||||||
|
m = one(entry("annotation", 9000, 2, image="/fb/x/annotated.png", marks=3, bundle="/fb/x"), "annotation")
|
||||||
|
assert m["label"] == "F12 annotation"
|
||||||
|
assert m["png"] == "/fb/x/annotated.png"
|
||||||
|
assert m["marks"] == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_real_engine_errors_are_moments() -> None:
|
||||||
|
row = entry("engine_error", 9000, 2, kind="script_error", message="boom " * 30, file="a.gd", line=3)
|
||||||
|
m = one(row, "engine_error")
|
||||||
|
assert m["error_kind"] == "script_error"
|
||||||
|
assert m["label"] == "engine_error " + ("boom " * 30)[:60]
|
||||||
|
assert (m["file"], m["line"]) == ("a.gd", 3)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("kind", ["warning", "stderr"])
|
||||||
|
def test_engine_noise_is_not_a_moment(kind: str) -> None:
|
||||||
|
assert moments.classify([entry("engine_error", 1, 1, kind=kind, message="x")], MOMENT_MAP) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_sim_events_the_game_may_log_later_pass_through() -> None:
|
||||||
|
m = one(entry("evt_wall_breached", 9000, 2, at=[1, 2], tag="v01"), "evt_wall_breached")
|
||||||
|
assert m["at"] == [1, 2]
|
||||||
|
assert "tag" not in m
|
||||||
|
assert "session" not in m
|
||||||
|
one(entry("milestone_first_win", 9000, 2), "milestone_first_win")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("name", ["recording_sync", "screen", "hitch", "", "perf"])
|
||||||
|
def test_everything_else_is_not_a_moment(name: str) -> None:
|
||||||
|
assert moments.classify([entry(name, 9000, 2)], MOMENT_MAP) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_event_name_is_the_event_field() -> None:
|
||||||
|
assert moments.event_name({"event": "buy"}) == "buy"
|
||||||
|
assert moments.event_name({}) == ""
|
||||||
150
game_recording/game_recording/tests/test_finalize.py
Normal file
150
game_recording/game_recording/tests/test_finalize.py
Normal file
@ -0,0 +1,150 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""After the game exits: events.json, chapters remuxed in, no re-encode."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from game_recording import finalize
|
||||||
|
from game_recording.tests.test_helpers import MOMENT_MAP, SESSION, SYNC_MS, SYNC_UNIX, entry, sync_entry
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
T0 = SYNC_UNIX + 0.5
|
||||||
|
START = 0.052
|
||||||
|
|
||||||
|
|
||||||
|
def make_video(path: Path) -> None:
|
||||||
|
"""A 4 s test pattern + tone whose timeline starts at START (like the real recorder's)."""
|
||||||
|
cmd = ["ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=160x120:rate=30"]
|
||||||
|
cmd += ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000", "-t", "4"]
|
||||||
|
cmd += ["-output_ts_offset", str(START), "-c:v", "libx264", "-c:a", "flac", str(path)]
|
||||||
|
subprocess.run(cmd, check=True, timeout=30)
|
||||||
|
|
||||||
|
|
||||||
|
def ffprobe(*args: str) -> dict[str, Any]:
|
||||||
|
cmd = ["ffprobe", "-v", "error", "-of", "json", *args]
|
||||||
|
out = subprocess.run(cmd, capture_output=True, text=True, check=True)
|
||||||
|
probed: dict[str, Any] = json.loads(out.stdout)
|
||||||
|
return probed
|
||||||
|
|
||||||
|
|
||||||
|
def write_meta(root: Path, rec: Path, extra: dict[str, object]) -> Path:
|
||||||
|
"""A rec.json for a single video file next to the feedback log."""
|
||||||
|
meta = {
|
||||||
|
"session": SESSION,
|
||||||
|
"t0_unix": T0,
|
||||||
|
"video": f"{SESSION}.mkv",
|
||||||
|
"feedback": str(root / "feedback.jsonl"),
|
||||||
|
**extra,
|
||||||
|
}
|
||||||
|
path = rec / f"{SESSION}.rec.json"
|
||||||
|
path.write_text(json.dumps(meta), encoding="utf-8")
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def session(tmp_path_factory: pytest.TempPathFactory) -> tuple[Path, dict[str, Any]]:
|
||||||
|
root = tmp_path_factory.mktemp("session")
|
||||||
|
rec = root / "recordings"
|
||||||
|
rec.mkdir()
|
||||||
|
make_video(rec / f"{SESSION}.mkv")
|
||||||
|
rows = [
|
||||||
|
sync_entry(),
|
||||||
|
entry("game_start", SYNC_MS + 100, 2, game="watch"),
|
||||||
|
entry("command", SYNC_MS + 1500, 3, order="rally", pos=[1, 2]),
|
||||||
|
entry("buy", SYNC_MS + 2500, 4, buff="stew", bought=True, cost=1),
|
||||||
|
entry("game_end", SYNC_MS + 3300, 5, game="watch", outcome="lose", elapsed_s=3.2),
|
||||||
|
]
|
||||||
|
(root / "feedback.jsonl").write_text("\n".join(json.dumps(r) for r in rows) + "\n", encoding="utf-8")
|
||||||
|
meta_path = write_meta(root, rec, {"encoder": "libx264"})
|
||||||
|
return rec, finalize.finalize(meta_path, MOMENT_MAP)
|
||||||
|
|
||||||
|
|
||||||
|
def test_events_json_is_written_with_timestamps_inside_the_duration(session: tuple[Path, dict[str, Any]]) -> None:
|
||||||
|
rec, doc = session
|
||||||
|
written = json.loads((rec / f"{SESSION}.events.json").read_text(encoding="utf-8"))
|
||||||
|
assert written["events"] == doc["events"]
|
||||||
|
assert written["video"]["encoder"] == "libx264"
|
||||||
|
assert written["video"]["file"] == f"{SESSION}.mkv"
|
||||||
|
end = written["video"]["end_s"]
|
||||||
|
inside = [e for e in written["events"] if not e.get("before_recording")]
|
||||||
|
assert inside
|
||||||
|
for event in inside:
|
||||||
|
assert START - 1e-3 <= event["t"] <= end + 1e-3
|
||||||
|
|
||||||
|
|
||||||
|
def test_video_start_and_duration_come_from_the_file(session: tuple[Path, dict[str, Any]]) -> None:
|
||||||
|
doc = session[1]
|
||||||
|
assert doc["video"]["start_s"] == pytest.approx(START, abs=1e-2)
|
||||||
|
assert doc["video"]["duration_s"] > 3.5
|
||||||
|
|
||||||
|
|
||||||
|
def test_chapters_are_embedded_without_reencoding_or_moving_the_timeline(
|
||||||
|
session: tuple[Path, dict[str, Any]],
|
||||||
|
) -> None:
|
||||||
|
rec, doc = session
|
||||||
|
info = ffprobe("-show_chapters", "-show_streams", str(rec / f"{SESSION}.mkv"))
|
||||||
|
starts = [float(c["start_time"]) for c in info["chapters"]]
|
||||||
|
expected = [e["t"] for e in doc["events"] if not e.get("before_recording")]
|
||||||
|
assert len(starts) == len(expected)
|
||||||
|
for got, want in zip(starts, expected, strict=True):
|
||||||
|
assert got == pytest.approx(want, abs=1e-2)
|
||||||
|
video = next(s for s in info["streams"] if s["codec_type"] == "video")
|
||||||
|
assert video["codec_name"] == "h264"
|
||||||
|
assert float(video["start_time"]) == pytest.approx(START, abs=1e-2)
|
||||||
|
assert not (rec / f"{SESSION}.ffmeta").exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_first_run_game_start_before_the_recorder_is_flagged(session: tuple[Path, dict[str, Any]]) -> None:
|
||||||
|
start = next(e for e in session[1]["events"] if e["kind"] == "game_start")
|
||||||
|
assert start.get("before_recording")
|
||||||
|
|
||||||
|
|
||||||
|
def test_finalize_is_repeatable(session: tuple[Path, dict[str, Any]]) -> None:
|
||||||
|
rec, doc = session
|
||||||
|
again = finalize.finalize(rec / f"{SESSION}.rec.json", MOMENT_MAP)
|
||||||
|
assert [e["t"] for e in again["events"]] == [e["t"] for e in doc["events"]]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_file_without_a_duration_is_scanned_whole(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
video = tmp_path / "open.mkv"
|
||||||
|
make_video(video)
|
||||||
|
real = finalize._ffprobe
|
||||||
|
|
||||||
|
def fake(*args: str) -> dict[str, Any]:
|
||||||
|
return {"format": {"start_time": "0.5"}} if "format=start_time,duration" in args else real(*args)
|
||||||
|
|
||||||
|
monkeypatch.setattr(finalize, "_ffprobe", fake)
|
||||||
|
start, duration = finalize.probe_span(video)
|
||||||
|
assert start == 0.5
|
||||||
|
assert duration > 3.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_file_without_packets_has_no_duration(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
def fake(*args: str) -> dict[str, Any]:
|
||||||
|
return {"format": {"start_time": "0.5"}} if "format=start_time,duration" in args else {"packets": [{}]}
|
||||||
|
|
||||||
|
monkeypatch.setattr(finalize, "_ffprobe", fake)
|
||||||
|
assert finalize.probe_span(tmp_path / "x.mkv") == (0.5, 0.0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_first_frame_for_a_missing_part_is_ignored(tmp_path: Path) -> None:
|
||||||
|
(tmp_path / "feedback.jsonl").write_text(json.dumps(sync_entry()) + "\n", encoding="utf-8")
|
||||||
|
make_video(tmp_path / f"{SESSION}.mkv")
|
||||||
|
meta = write_meta(tmp_path, tmp_path, {"first_frame_unix": {"gone.mkv": T0}})
|
||||||
|
assert finalize.finalize(meta, MOMENT_MAP)["video"]["start_s"] == pytest.approx(START, abs=1e-2)
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_unaligned_gsr_part_is_moved_once_and_stays_put(tmp_path: Path) -> None:
|
||||||
|
"""A gsr part starts at 0; rec.json says when its first frame was, finalize puts it on the t0 timeline."""
|
||||||
|
cmd = ["ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=160x120:rate=30", "-t", "2"]
|
||||||
|
subprocess.run([*cmd, "-c:v", "libx264", str(tmp_path / f"{SESSION}.mkv")], check=True, timeout=30)
|
||||||
|
(tmp_path / "feedback.jsonl").write_text(json.dumps(sync_entry()) + "\n", encoding="utf-8")
|
||||||
|
meta = write_meta(tmp_path, tmp_path, {"first_frame_unix": {f"{SESSION}.mkv": T0 + 2.0}})
|
||||||
|
for _ in range(2):
|
||||||
|
doc = finalize.finalize(meta, MOMENT_MAP)
|
||||||
|
assert doc["video"]["start_s"] == pytest.approx(2.0, abs=1e-2)
|
||||||
87
game_recording/game_recording/tests/test_gsr.py
Normal file
87
game_recording/game_recording/tests/test_gsr.py
Normal file
@ -0,0 +1,87 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""gpu-screen-recorder backend: argv, backend choice, first-frame time."""
|
||||||
|
|
||||||
|
from itertools import pairwise
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from game_recording import encoder, gsr
|
||||||
|
from game_recording.tests.test_helpers import CONFIG
|
||||||
|
|
||||||
|
SPEC = encoder.Spec(window_id=39845893, fps=30, t0_unix=1_800_000_000.5, out="/o/s.mkv", audio="default")
|
||||||
|
TS_TEXT = "monotonic_microsec\trealtime_microsec\n8935499369\t1794415951373572\n"
|
||||||
|
ENV_NAME = "DEMO_RECORDER_BACKEND"
|
||||||
|
|
||||||
|
|
||||||
|
def _pairs(spec: encoder.Spec = SPEC) -> list[tuple[str, str]]:
|
||||||
|
return list(pairwise(gsr.command(spec)))
|
||||||
|
|
||||||
|
|
||||||
|
def test_records_the_window_on_the_gpu_at_the_fps() -> None:
|
||||||
|
cmd = gsr.command(SPEC)
|
||||||
|
assert cmd[0] == "gpu-screen-recorder"
|
||||||
|
pairs = _pairs()
|
||||||
|
for pair in (("-w", "39845893"), ("-f", "30"), ("-k", "h264"), ("-c", "mkv"), ("-o", "/o/s.mkv")):
|
||||||
|
assert pair in pairs
|
||||||
|
assert "x11grab" not in cmd
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_first_frame_time_is_written_for_the_timeline() -> None:
|
||||||
|
assert ("-write-first-frame-ts", "yes") in _pairs()
|
||||||
|
|
||||||
|
|
||||||
|
def test_constant_frame_rate_without_the_cursor_and_quiet() -> None:
|
||||||
|
pairs = _pairs()
|
||||||
|
for pair in (("-fm", "cfr"), ("-cursor", "no"), ("-v", "no"), ("-q", "very_high")):
|
||||||
|
assert pair in pairs
|
||||||
|
|
||||||
|
|
||||||
|
def test_audio_is_the_default_output_as_opus_because_flac_is_disabled_in_gsr() -> None:
|
||||||
|
pairs = _pairs()
|
||||||
|
assert ("-a", "default_output") in pairs
|
||||||
|
assert ("-ac", "opus") in pairs
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_named_pulse_source_is_a_device() -> None:
|
||||||
|
spec = encoder.Spec(window_id=1, fps=30, t0_unix=0.0, out="/o/s.mkv", audio="sink.monitor")
|
||||||
|
assert ("-a", "device:sink.monitor") in _pairs(spec)
|
||||||
|
|
||||||
|
|
||||||
|
def test_ts_file_sits_next_to_the_video_with_an_extra_extension() -> None:
|
||||||
|
assert gsr.ts_path("/o/s.mkv") == Path("/o/s.mkv.ts")
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_realtime_column_is_the_unix_time() -> None:
|
||||||
|
assert gsr.parse_first_frame(TS_TEXT) == pytest.approx(1794415951.373572, abs=1e-6)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"text",
|
||||||
|
["", "monotonic_microsec\trealtime_microsec\n", TS_TEXT.rstrip("\n"), "x\ty\n1\t2z\n", "1\t2\t3\n"],
|
||||||
|
)
|
||||||
|
def test_a_missing_or_partial_file_is_not_a_time_yet(text: str) -> None:
|
||||||
|
assert gsr.parse_first_frame(text) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_measured_capture_latency_is_between_two_and_three_frames_at_30_fps() -> None:
|
||||||
|
assert 2 / 30 < gsr.CAPTURE_LATENCY_S < 3 / 30
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("env", "audio", "want", "have_gsr"),
|
||||||
|
[
|
||||||
|
({}, "default", "gsr", True),
|
||||||
|
({}, "default", "x11grab", False),
|
||||||
|
({ENV_NAME: "x11grab"}, "default", "x11grab", True),
|
||||||
|
({ENV_NAME: "gsr"}, "default", "gsr", True),
|
||||||
|
({}, "lavfi", "x11grab", True),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_backend_choice(env: dict[str, str], audio: str, want: str, *, have_gsr: bool) -> None:
|
||||||
|
assert gsr.pick_backend(env, audio, CONFIG, have_gsr=have_gsr) == want
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_env_name_comes_from_the_config_prefix() -> None:
|
||||||
|
assert CONFIG.env_name(gsr.BACKEND_SUFFIX) == ENV_NAME
|
||||||
|
assert gsr.pick_backend({"OTHER_RECORDER_BACKEND": "x11grab"}, "default", CONFIG, have_gsr=True) == "gsr"
|
||||||
108
game_recording/game_recording/tests/test_gsr_start.py
Normal file
108
game_recording/game_recording/tests/test_gsr_start.py
Normal file
@ -0,0 +1,108 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""gpu-screen-recorder: starting it, and moving a finished part onto the timeline."""
|
||||||
|
|
||||||
|
from itertools import pairwise
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import stat
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from game_recording import encoder, gsr
|
||||||
|
|
||||||
|
FAKE_GSR = """#!{python}
|
||||||
|
import os, pathlib, signal, sys, time
|
||||||
|
args = sys.argv[1:]
|
||||||
|
out = args[args.index("-o") + 1]
|
||||||
|
mode = os.environ.get("FAKE_GSR", "ok")
|
||||||
|
if mode == "die":
|
||||||
|
sys.exit(1)
|
||||||
|
if mode == "ok":
|
||||||
|
pathlib.Path(out + ".ts").write_text("monotonic_microsec\\trealtime_microsec\\n5\\t1800000007250000\\n")
|
||||||
|
signal.signal(signal.SIGINT, lambda *_: sys.exit(0))
|
||||||
|
time.sleep(60)
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def install_fake(folder: Path) -> None:
|
||||||
|
path = folder / "gpu-screen-recorder"
|
||||||
|
path.write_text(FAKE_GSR.format(python=sys.executable), encoding="utf-8")
|
||||||
|
path.chmod(path.stat().st_mode | stat.S_IXUSR)
|
||||||
|
|
||||||
|
|
||||||
|
def _start(
|
||||||
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mode: str, wait_s: float = 5.0
|
||||||
|
) -> tuple[subprocess.Popen[bytes], float] | None:
|
||||||
|
install_fake(tmp_path)
|
||||||
|
monkeypatch.setenv("PATH", f"{tmp_path}{os.pathsep}{os.environ['PATH']}")
|
||||||
|
monkeypatch.setenv("FAKE_GSR", mode)
|
||||||
|
spec = encoder.Spec(window_id=1, fps=30, t0_unix=0.0, out=str(tmp_path / "s.mkv"))
|
||||||
|
with (tmp_path / "log").open("ab") as log:
|
||||||
|
return gsr.start(spec, log, "0", wait_s=wait_s)
|
||||||
|
|
||||||
|
|
||||||
|
def test_available_follows_the_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
monkeypatch.setenv("PATH", str(tmp_path))
|
||||||
|
assert not gsr.available()
|
||||||
|
install_fake(tmp_path)
|
||||||
|
assert gsr.available()
|
||||||
|
|
||||||
|
|
||||||
|
def test_returns_the_running_recorder_and_its_first_frame_unix_time(
|
||||||
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||||
|
) -> None:
|
||||||
|
started = _start(tmp_path, monkeypatch, "ok")
|
||||||
|
assert started is not None
|
||||||
|
proc, first = started
|
||||||
|
try:
|
||||||
|
assert proc.poll() is None
|
||||||
|
# gsr stamps its first frame after the screen showed it (measured on :0, bench.sh sync)
|
||||||
|
assert first == pytest.approx(1_800_000_007.25 - gsr.CAPTURE_LATENCY_S, abs=1e-6)
|
||||||
|
finally:
|
||||||
|
proc.kill()
|
||||||
|
proc.wait()
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_recorder_that_dies_at_start_is_a_failure(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
assert _start(tmp_path, monkeypatch, "die") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_recorder_that_never_stamps_its_first_frame_is_killed_and_a_failure(
|
||||||
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||||
|
) -> None:
|
||||||
|
assert _start(tmp_path, monkeypatch, "nots", wait_s=1.0) is None
|
||||||
|
assert not (tmp_path / "s.mkv.ts").exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_delta_puts_the_first_frame_on_the_t0_timeline() -> None:
|
||||||
|
assert gsr.shift_delta(first_unix=107.0, t0=100.0, first_stamp=0.0) == pytest.approx(7.0)
|
||||||
|
assert gsr.shift_delta(first_unix=107.0, t0=100.0, first_stamp=0.25) == pytest.approx(6.75)
|
||||||
|
|
||||||
|
|
||||||
|
def test_shift_command_copies_streams_and_moves_the_stamps() -> None:
|
||||||
|
cmd = gsr.shift_command(Path("/o/a.mkv"), Path("/o/a.shift.mkv"), 7.0)
|
||||||
|
pairs = list(pairwise(cmd))
|
||||||
|
assert ("-output_ts_offset", "7.000000") in pairs
|
||||||
|
assert ("-c", "copy") in pairs
|
||||||
|
assert "-copyts" in cmd
|
||||||
|
assert cmd[-1] == "/o/a.shift.mkv"
|
||||||
|
|
||||||
|
|
||||||
|
def test_align_moves_a_real_file_onto_the_timeline(tmp_path: Path) -> None:
|
||||||
|
video = tmp_path / "p.mkv"
|
||||||
|
cmd = ["ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=160x120:rate=30", "-t", "1"]
|
||||||
|
subprocess.run([*cmd, "-c:v", "libx264", str(video)], check=True, timeout=30)
|
||||||
|
assert gsr.video_start(video) == pytest.approx(0.0, abs=1e-3)
|
||||||
|
gsr.align(video, first_unix=107.0, t0=100.0)
|
||||||
|
assert gsr.video_start(video) == pytest.approx(7.0, abs=1e-2)
|
||||||
|
assert [p.name for p in tmp_path.iterdir()] == ["p.mkv"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_file_already_on_the_timeline_is_left_alone(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
video = tmp_path / "p.mkv"
|
||||||
|
video.write_bytes(b"not a video") # would make ffprobe/ffmpeg fail if touched
|
||||||
|
monkeypatch.setattr(gsr, "video_start", lambda _video: 0.0005)
|
||||||
|
gsr.align(video, first_unix=100.0, t0=100.0)
|
||||||
|
assert video.read_bytes() == b"not a video"
|
||||||
48
game_recording/game_recording/tests/test_helpers.py
Normal file
48
game_recording/game_recording/tests/test_helpers.py
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""Shared fixtures for the recorder tests: a made-up game's config and telemetry lines."""
|
||||||
|
|
||||||
|
from game_recording import moments
|
||||||
|
from game_recording.config import COMMON_DIRECT, Config, Moment, MomentMap, Row
|
||||||
|
|
||||||
|
SESSION = "1794396071-c6df"
|
||||||
|
# The game's clock: `ms` counts from the log's creation; the sync entry pairs one
|
||||||
|
# ms value with the unix time of that same instant.
|
||||||
|
SYNC_UNIX = 1_800_000_000.250
|
||||||
|
SYNC_MS = 200
|
||||||
|
|
||||||
|
MOMENT_MAP = MomentMap(
|
||||||
|
direct={
|
||||||
|
**COMMON_DIRECT,
|
||||||
|
"buy": ("buff", "bought", "cost"),
|
||||||
|
"game_start": ("loadout", "cost", "men", "seed"),
|
||||||
|
"command": ("order", "pos"),
|
||||||
|
"lab_result": ("wins", "runs", "mean_seconds"),
|
||||||
|
"reset_progress": ("files",),
|
||||||
|
},
|
||||||
|
passthrough_prefixes=("evt_", "milestone"),
|
||||||
|
)
|
||||||
|
CONFIG = Config(binaries_dir="data/demo_binaries", env_prefix="DEMO", moments=MOMENT_MAP)
|
||||||
|
|
||||||
|
|
||||||
|
def entry(event: str, ms: int, seq: int = 0, **fields: object) -> Row:
|
||||||
|
"""One telemetry line as the game writes it."""
|
||||||
|
return {
|
||||||
|
"event": event,
|
||||||
|
"session": SESSION,
|
||||||
|
"seq": seq,
|
||||||
|
"ms": ms,
|
||||||
|
"frame": ms // 16,
|
||||||
|
"time": "2026-11-11T12:00:00",
|
||||||
|
**fields,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def sync_entry() -> Row:
|
||||||
|
"""The line that pairs the game clock with unix time."""
|
||||||
|
return entry("recording_sync", SYNC_MS, 1, unix=SYNC_UNIX)
|
||||||
|
|
||||||
|
|
||||||
|
def classify_one(row: Row, moment_map: MomentMap = MOMENT_MAP) -> Moment | None:
|
||||||
|
"""The one moment a line becomes, None when it is not one."""
|
||||||
|
found = moments.classify([row], moment_map)
|
||||||
|
return found[0] if found else None
|
||||||
145
game_recording/game_recording/tests/test_library.py
Normal file
145
game_recording/game_recording/tests/test_library.py
Normal file
@ -0,0 +1,145 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""Listing and opening a recording at a moment."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from game_recording import library
|
||||||
|
|
||||||
|
DOC: dict[str, Any] = {
|
||||||
|
"session": "s1",
|
||||||
|
"tag": "v02",
|
||||||
|
"video": {"start_s": 0.052, "duration_s": 100.0, "end_s": 100.052, "file": "s1.mkv"},
|
||||||
|
"sync": {"approx": False},
|
||||||
|
"events": [
|
||||||
|
{"t": -2.0, "label": "game_start watch", "before_recording": True},
|
||||||
|
{"t": 1.0, "label": "pause_open"},
|
||||||
|
{"t": 42.5, "label": "command rally"},
|
||||||
|
{"t": 400.0, "label": "late", "after_recording": True},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
PARTED: dict[str, Any] = {
|
||||||
|
"session": "s2",
|
||||||
|
"video": {
|
||||||
|
"start_s": 0.05,
|
||||||
|
"duration_s": 30.0,
|
||||||
|
"end_s": 30.05,
|
||||||
|
"file": "s2.mkv",
|
||||||
|
"parts": [
|
||||||
|
{"file": "s2.mkv", "start_s": 0.05, "duration_s": 10.0},
|
||||||
|
{"file": "s2.part2.mkv", "start_s": 20.0, "duration_s": 10.0},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"sync": {"approx": False},
|
||||||
|
"events": [
|
||||||
|
{"t": 5.0, "label": "a", "file": "s2.mkv"},
|
||||||
|
{"t": 15.0, "label": "in the gap", "in_gap": True},
|
||||||
|
{"t": 21.0, "label": "b", "file": "s2.part2.mkv"},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def write(folder: Path, name: str, doc: dict[str, Any], mtime: int) -> Path:
|
||||||
|
path = folder / f"{name}.events.json"
|
||||||
|
path.write_text(json.dumps(doc), encoding="utf-8")
|
||||||
|
os.utime(path, (mtime, mtime))
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(("seconds", "text"), [(75.5, "01:15.500"), (0.0, "00:00.000"), (-1.5, "-00:01.500")])
|
||||||
|
def test_stamp_is_minutes_seconds_millis(seconds: float, text: str) -> None:
|
||||||
|
assert library.stamp(seconds) == text
|
||||||
|
|
||||||
|
|
||||||
|
def test_table_numbers_only_moments_inside_the_file() -> None:
|
||||||
|
lines = library.table(DOC).splitlines()
|
||||||
|
assert lines[0] == "s1 v02 01:40.000 s1.mkv"
|
||||||
|
assert len(lines) == 3
|
||||||
|
assert lines[1] == " 1 00:01.000 pause_open"
|
||||||
|
assert lines[2] == " 2 00:42.500 command rally"
|
||||||
|
|
||||||
|
|
||||||
|
def test_open_seeks_a_little_before_the_moment_on_the_files_own_timeline() -> None:
|
||||||
|
cmd = library.open_command(DOC, Path("/rec"), 2)
|
||||||
|
assert cmd[0] == "mpv"
|
||||||
|
assert "--rebase-start-time=no" in cmd
|
||||||
|
assert "--start=39.500" in cmd
|
||||||
|
assert cmd[-1] == "/rec/s1.mkv"
|
||||||
|
|
||||||
|
|
||||||
|
def test_open_never_seeks_before_the_first_frame() -> None:
|
||||||
|
assert "--start=0.052" in library.open_command(DOC, Path("/rec"), 1)
|
||||||
|
|
||||||
|
|
||||||
|
def test_open_without_a_number_plays_from_the_start() -> None:
|
||||||
|
assert not any(a.startswith("--start") for a in library.open_command(DOC, Path("/rec"), None))
|
||||||
|
|
||||||
|
|
||||||
|
def test_open_of_a_missing_moment_says_the_range() -> None:
|
||||||
|
with pytest.raises(IndexError, match=r"no moment 9 \(1\.\.2\)"):
|
||||||
|
library.open_command(DOC, Path("/rec"), 9)
|
||||||
|
|
||||||
|
|
||||||
|
def test_gap_moments_are_not_listed() -> None:
|
||||||
|
assert [e["label"] for e in library.shown(PARTED)] == ["a", "b"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_open_uses_the_part_that_holds_the_moment() -> None:
|
||||||
|
cmd = library.open_command(PARTED, Path("/rec"), 2)
|
||||||
|
assert cmd[-1] == "/rec/s2.part2.mkv"
|
||||||
|
assert "--start=20.000" in cmd, "clamped to the part's first frame, not 18.0"
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_table_says_the_window_went_away() -> None:
|
||||||
|
text = library.table(PARTED)
|
||||||
|
assert "2 parts" in text
|
||||||
|
assert "[s2.part2.mkv]" in text
|
||||||
|
|
||||||
|
|
||||||
|
def test_sessions_are_listed_newest_first_and_load_back(tmp_path: Path) -> None:
|
||||||
|
old = write(tmp_path, "old", {**DOC, "session": "old"}, 1_000)
|
||||||
|
new = write(tmp_path, "new", {**DOC, "session": "new"}, 2_000)
|
||||||
|
assert library.sessions(tmp_path) == [new, old]
|
||||||
|
assert library.load(new)["session"] == "new"
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_listing_has_one_line_per_session(tmp_path: Path) -> None:
|
||||||
|
write(tmp_path, "a", DOC, 1_000)
|
||||||
|
assert library.listing(tmp_path) == "s1 01:40.000 2 moments v02"
|
||||||
|
assert library.listing(tmp_path / "none") == ""
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_png_and_an_approximate_sync_show_in_the_table() -> None:
|
||||||
|
doc = {**DOC, "sync": {"approx": True}, "events": [{"t": -1.5, "label": "x", "png": "x.png"}]}
|
||||||
|
lines = library.table(doc).splitlines()
|
||||||
|
assert "+-1 s" in lines[1]
|
||||||
|
assert lines[2] == " 1 -00:01.500 x x.png"
|
||||||
|
|
||||||
|
|
||||||
|
def test_open_moment_prints_the_command_on_a_dry_run(capsys: pytest.CaptureFixture[str]) -> None:
|
||||||
|
assert library.open_moment(DOC, Path("/rec"), 2, dry_run=True) == 0
|
||||||
|
assert capsys.readouterr().out.split() == [
|
||||||
|
"mpv",
|
||||||
|
"--rebase-start-time=no",
|
||||||
|
"--force-window=yes",
|
||||||
|
"--start=39.500",
|
||||||
|
"/rec/s1.mkv",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_open_moment_runs_the_player_and_returns_its_exit_code(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
seen: list[list[str]] = []
|
||||||
|
|
||||||
|
def call(cmd: list[str]) -> int:
|
||||||
|
seen.append(cmd)
|
||||||
|
return 3
|
||||||
|
|
||||||
|
monkeypatch.setattr(subprocess, "call", call)
|
||||||
|
assert library.open_moment(DOC, Path("/rec"), None, dry_run=False) == 3
|
||||||
|
assert seen[0][-1] == "/rec/s1.mkv"
|
||||||
138
game_recording/game_recording/tests/test_moment_map.py
Normal file
138
game_recording/game_recording/tests/test_moment_map.py
Normal file
@ -0,0 +1,138 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""A second, made-up game adopts the package by configuration alone."""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from game_recording import moments
|
||||||
|
from game_recording.config import COMMON_DIRECT, Config, Moment, MomentMap, Row
|
||||||
|
from game_recording.tests.test_helpers import entry
|
||||||
|
|
||||||
|
|
||||||
|
def boss_hit(row: Row) -> Moment | None:
|
||||||
|
if row.get("event") != "boss_hit":
|
||||||
|
return None
|
||||||
|
return moments.moment(row, "boss", "hit the boss", dmg=row.get("dmg"))
|
||||||
|
|
||||||
|
|
||||||
|
def never(_row: Row) -> Moment | None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def hijack_buy(row: Row) -> Moment | None:
|
||||||
|
return moments.moment(row, "hijacked", "custom") if row.get("event") == "buy" else None
|
||||||
|
|
||||||
|
|
||||||
|
def second(_row: Row) -> Moment | None:
|
||||||
|
return moments.moment({"ms": 1}, "second", "second")
|
||||||
|
|
||||||
|
|
||||||
|
def ammo_low(rows: list[Row]) -> list[Moment]:
|
||||||
|
return [moments.moment(r, "ammo_low", "ammo low") for r in rows if r.get("ammo", 99) < 5]
|
||||||
|
|
||||||
|
|
||||||
|
def classify(rows: list[Row], moment_map: MomentMap) -> list[Moment]:
|
||||||
|
return moments.classify(rows, moment_map)
|
||||||
|
|
||||||
|
|
||||||
|
def test_default_map_has_only_the_common_events() -> None:
|
||||||
|
plain = MomentMap()
|
||||||
|
assert plain.direct is COMMON_DIRECT
|
||||||
|
assert plain.passthrough_prefixes == ()
|
||||||
|
assert classify([entry("hub_open", 1)], plain)[0]["kind"] == "hub_open"
|
||||||
|
assert classify([entry("buy", 1)], plain) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_game_adds_its_own_direct_events() -> None:
|
||||||
|
game = MomentMap(direct={**COMMON_DIRECT, "loot": ("item",)})
|
||||||
|
found = classify([entry("loot", 5, 1, game="g", item="axe")], game)
|
||||||
|
assert found[0]["label"] == "loot g axe"
|
||||||
|
assert found[0]["item"] == "axe"
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_passthrough_prefixes_pass_nothing_through() -> None:
|
||||||
|
assert classify([entry("evt_x", 1), entry("", 2)], MomentMap()) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_set_passthrough_prefixes_pass_matching_events() -> None:
|
||||||
|
game = MomentMap(passthrough_prefixes=("quest_",))
|
||||||
|
found = classify([entry("quest_done", 1, 1, stars=3), entry("evt_x", 2)], game)
|
||||||
|
assert [m["kind"] for m in found] == ["quest_done"]
|
||||||
|
assert found[0]["stars"] == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_game_end_fields_are_configurable() -> None:
|
||||||
|
game = MomentMap(game_end_fields=("score",))
|
||||||
|
m = classify([entry("game_end", 1, 1, outcome="win", score=9, elapsed_s=4)], game)[0]
|
||||||
|
assert m["score"] == 9
|
||||||
|
assert "elapsed_s" not in m
|
||||||
|
assert m["label"] == "game_end win"
|
||||||
|
|
||||||
|
|
||||||
|
def test_game_end_without_an_outcome_has_a_bare_label() -> None:
|
||||||
|
assert classify([entry("game_end", 1)], MomentMap())[0]["label"] == "game_end"
|
||||||
|
|
||||||
|
|
||||||
|
def test_error_kinds_are_configurable() -> None:
|
||||||
|
game = MomentMap(error_kinds=frozenset({"stderr"}))
|
||||||
|
assert classify([entry("engine_error", 1, kind="stderr", message="x")], game)[0]["error_kind"] == "stderr"
|
||||||
|
assert classify([entry("engine_error", 1, kind="script_error", message="x")], game) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_hitch_merge_s_override_changes_the_burst() -> None:
|
||||||
|
rows = [entry("hitch", 1000, 1, dur_ms=1), entry("hitch", 1500, 2, dur_ms=2)]
|
||||||
|
assert len(moments.derive(rows, MomentMap(hitch_merge_s=0.1))) == 2
|
||||||
|
assert len(moments.derive(rows, MomentMap(hitch_merge_s=5.0))) == 1
|
||||||
|
assert MomentMap().hitch_merge_s == 2.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_classifier_hook_makes_a_moment_the_built_ins_do_not() -> None:
|
||||||
|
game = MomentMap(classifiers=(boss_hit,))
|
||||||
|
found = classify([entry("boss_hit", 7, 1, dmg=12), entry("hub_open", 8, 2)], game)
|
||||||
|
assert [m["kind"] for m in found] == ["boss", "hub_open"]
|
||||||
|
assert found[0]["dmg"] == 12
|
||||||
|
|
||||||
|
|
||||||
|
def test_classifier_hooks_run_before_built_ins() -> None:
|
||||||
|
game = MomentMap(direct={**COMMON_DIRECT, "buy": ()}, classifiers=(hijack_buy,))
|
||||||
|
assert classify([entry("buy", 1)], game)[0]["kind"] == "hijacked"
|
||||||
|
|
||||||
|
|
||||||
|
def test_first_non_none_classifier_wins() -> None:
|
||||||
|
game = MomentMap(classifiers=(never, boss_hit, second))
|
||||||
|
assert classify([entry("boss_hit", 1, 1)], game)[0]["kind"] == "boss"
|
||||||
|
assert classify([entry("other", 1, 1)], game)[0]["kind"] == "second"
|
||||||
|
|
||||||
|
|
||||||
|
def test_session_rule_hook_moments_join_the_hitch_burst() -> None:
|
||||||
|
game = MomentMap(session_rules=(ammo_low,))
|
||||||
|
rows = [entry("hitch", 1000, 1, dur_ms=5), entry("shot", 2000, 2, ammo=3), entry("shot", 3000, 3, ammo=40)]
|
||||||
|
found = moments.derive(rows, game)
|
||||||
|
assert [m["kind"] for m in found] == ["hitch", "ammo_low"]
|
||||||
|
assert moments.derive(rows, MomentMap()) == found[:1]
|
||||||
|
|
||||||
|
|
||||||
|
def test_moment_builder_fields() -> None:
|
||||||
|
row = entry("evt_x", 42, 9, game="g")
|
||||||
|
m = moments.moment(row, "kind", "label", extra=1)
|
||||||
|
assert m == {"kind": "kind", "label": "label", "event": "evt_x", "seq": 9, "ms": 42, "game": "g", "extra": 1}
|
||||||
|
|
||||||
|
|
||||||
|
def test_moment_builder_omits_an_empty_game() -> None:
|
||||||
|
assert "game" not in moments.moment(entry("evt_x", 42), "k", "l")
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_env_names_use_the_prefix() -> None:
|
||||||
|
cfg = Config(binaries_dir="b", env_prefix="ZED")
|
||||||
|
assert cfg.env_name("NO_RECORD") == "ZED_NO_RECORD"
|
||||||
|
assert cfg.blocking_flags == ("ZED_NO_RECORD",)
|
||||||
|
assert cfg.moments == MomentMap()
|
||||||
|
|
||||||
|
|
||||||
|
def test_extra_blocking_flags_follow_the_no_record_flag() -> None:
|
||||||
|
cfg = Config(binaries_dir="b", env_prefix="ZED", extra_blocking_flags=("ZED_CI",))
|
||||||
|
assert cfg.blocking_flags == ("ZED_NO_RECORD", "ZED_CI")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(("override", "expected"), [("", "ZED_BINARIES"), ("MY_BINS", "MY_BINS")])
|
||||||
|
def test_binaries_var_defaults_and_overrides(override: str, expected: str) -> None:
|
||||||
|
assert Config(binaries_dir="b", env_prefix="ZED", binaries_env=override).binaries_var == expected
|
||||||
108
game_recording/game_recording/tests/test_policy.py
Normal file
108
game_recording/game_recording/tests/test_policy.py
Normal file
@ -0,0 +1,108 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""When a run is recorded (a person's dev play) and when never (bots, tests, headless)."""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from game_recording import policy
|
||||||
|
from game_recording.config import Config
|
||||||
|
from game_recording.tests.test_helpers import CONFIG
|
||||||
|
|
||||||
|
LIVE = {"DISPLAY": ":0"}
|
||||||
|
DEV = ["godot", "--", "--dev"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_dev_run_is_recorded() -> None:
|
||||||
|
decision = policy.decide(["godot", "--path", "/r", "--", "--dev"], LIVE, CONFIG)
|
||||||
|
assert decision.record, decision.reason
|
||||||
|
assert decision.reason == "dev play"
|
||||||
|
|
||||||
|
|
||||||
|
def test_exported_dev_build_is_recorded() -> None:
|
||||||
|
assert policy.decide(["/b/game.x86_64", "--", "--dev", "--dev-tag=v01"], LIVE, CONFIG).record
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("args", [["godot", "--"], ["godot", "--", "--no-dev", "--dev"]])
|
||||||
|
def test_no_dev_flag_means_no_recording(args: list[str]) -> None:
|
||||||
|
decision = policy.decide(args, LIVE, CONFIG)
|
||||||
|
assert not decision.record
|
||||||
|
assert decision.reason == "not a --dev run"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"marker", ["--autodrive=watch", "--result-file=/t/r", "--expect-window=1280x800", "--save-dir=/t"]
|
||||||
|
)
|
||||||
|
def test_each_bot_marker_blocks(marker: str) -> None:
|
||||||
|
decision = policy.decide(["godot", "--", "--dev", marker], LIVE, CONFIG)
|
||||||
|
assert not decision.record
|
||||||
|
assert marker in decision.reason
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"engine",
|
||||||
|
[["--headless"], ["--audio-driver", "Dummy"], ["--display-driver", "headless"]],
|
||||||
|
)
|
||||||
|
def test_headless_and_muted_engine_runs_block(engine: list[str]) -> None:
|
||||||
|
decision = policy.decide(["godot", *engine, "--", "--dev"], LIVE, CONFIG)
|
||||||
|
assert not decision.record
|
||||||
|
assert decision.reason.startswith("headless or muted run")
|
||||||
|
|
||||||
|
|
||||||
|
def test_engine_flags_after_the_double_dash_are_the_games_own() -> None:
|
||||||
|
assert policy.decide(["godot", "--", "--dev", "--headless"], LIVE, CONFIG).record
|
||||||
|
|
||||||
|
|
||||||
|
def test_engine_flag_without_a_value_or_with_another_value_does_not_block() -> None:
|
||||||
|
assert policy.decide(["godot", "--audio-driver", "--dev"], LIVE, CONFIG).record
|
||||||
|
assert policy.decide(["godot", "--audio-driver", "Pulse", "--dev"], LIVE, CONFIG).record
|
||||||
|
assert policy.decide(["godot", "--audio-driver"], LIVE, CONFIG).reason == "not a --dev run"
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_display_blocks() -> None:
|
||||||
|
decision = policy.decide(DEV, {}, CONFIG)
|
||||||
|
assert not decision.record
|
||||||
|
assert decision.reason == "no DISPLAY"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("env", "reason"),
|
||||||
|
[
|
||||||
|
({"DEMO_NO_RECORD": "1"}, "DEMO_NO_RECORD=1"),
|
||||||
|
({"DEMO_FEEDBACK_DIR": "/t"}, "DEMO_FEEDBACK_DIR is set"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_env_opt_outs_block(env: dict[str, str], reason: str) -> None:
|
||||||
|
decision = policy.decide(DEV, {**LIVE, **env}, CONFIG)
|
||||||
|
assert not decision.record
|
||||||
|
assert decision.reason == reason
|
||||||
|
|
||||||
|
|
||||||
|
def test_flag_set_to_zero_is_off() -> None:
|
||||||
|
assert policy.decide(DEV, {**LIVE, "DEMO_NO_RECORD": "0"}, CONFIG).record
|
||||||
|
|
||||||
|
|
||||||
|
def test_another_games_env_prefix_does_not_block() -> None:
|
||||||
|
assert policy.decide(DEV, {**LIVE, "OTHER_NO_RECORD": "1"}, CONFIG).record
|
||||||
|
|
||||||
|
|
||||||
|
def test_extra_blocking_flags_of_the_config_block() -> None:
|
||||||
|
config = Config(binaries_dir="b", env_prefix="DEMO", extra_blocking_flags=("DEMO_CI",))
|
||||||
|
assert policy.decide(DEV, {**LIVE, "DEMO_CI": "1"}, config).reason == "DEMO_CI=1"
|
||||||
|
|
||||||
|
|
||||||
|
def test_force_overrides_bot_rules_but_not_a_missing_display() -> None:
|
||||||
|
args = ["godot", "--audio-driver", "Dummy", "--", "--dev", "--autodrive", "--save-dir=/t"]
|
||||||
|
forced = policy.decide(args, LIVE, CONFIG, force=True)
|
||||||
|
assert forced.record
|
||||||
|
assert forced.reason == "forced"
|
||||||
|
assert not policy.decide(args, {}, CONFIG, force=True).record
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_reason_names_the_blocker() -> None:
|
||||||
|
assert "--autodrive" in policy.decide(["godot", "--", "--dev", "--autodrive"], LIVE, CONFIG).reason
|
||||||
|
|
||||||
|
|
||||||
|
def test_session_and_feedback_dir_come_from_the_args() -> None:
|
||||||
|
args = ["godot", "--", "--dev", "--session-id=abc", "--feedback-dir=/fb"]
|
||||||
|
assert policy.arg_value(args, "--session-id=") == "abc"
|
||||||
|
assert policy.arg_value(args, "--feedback-dir=") == "/fb"
|
||||||
|
assert policy.arg_value(args, "--nope=") == ""
|
||||||
63
game_recording/game_recording/tests/test_procs.py
Normal file
63
game_recording/game_recording/tests/test_procs.py
Normal file
@ -0,0 +1,63 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""Starting external programs: path lookup, nice wrapper, spawn with log, env and detach."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from game_recording import procs
|
||||||
|
|
||||||
|
|
||||||
|
def test_program_is_the_full_path_when_installed() -> None:
|
||||||
|
found = shutil.which("sh")
|
||||||
|
assert found is not None
|
||||||
|
assert procs.program("sh") == found
|
||||||
|
|
||||||
|
|
||||||
|
def test_program_keeps_the_bare_name_when_missing() -> None:
|
||||||
|
assert procs.program("no-such-program-xyz") == "no-such-program-xyz"
|
||||||
|
|
||||||
|
|
||||||
|
def test_niced_prefixes_the_resolved_nice() -> None:
|
||||||
|
argv = procs.niced("7", ["ffmpeg", "-i", "x"])
|
||||||
|
assert argv[1:] == ["-n", "7", "ffmpeg", "-i", "x"]
|
||||||
|
assert Path(argv[0]).name == "nice"
|
||||||
|
assert Path(argv[0]).is_absolute()
|
||||||
|
|
||||||
|
|
||||||
|
def test_spawn_runs_the_child_without_a_log() -> None:
|
||||||
|
proc = procs.spawn([sys.executable, "-c", "pass"])
|
||||||
|
assert proc.wait(timeout=20) == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_spawn_sends_output_to_the_log(tmp_path: Path) -> None:
|
||||||
|
out = tmp_path / "out.log"
|
||||||
|
with out.open("wb") as log:
|
||||||
|
proc = procs.spawn([sys.executable, "-c", "import sys; print('o'); print('e', file=sys.stderr)"], log=log)
|
||||||
|
assert proc.wait(timeout=20) == 0
|
||||||
|
assert sorted(out.read_text().split()) == ["e", "o"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_spawn_passes_the_given_env(tmp_path: Path) -> None:
|
||||||
|
out = tmp_path / "env.log"
|
||||||
|
code = "import os; print(os.environ['SPAWN_PROBE'], 'PATH' in os.environ)"
|
||||||
|
with out.open("wb") as log:
|
||||||
|
proc = procs.spawn([sys.executable, "-c", code], env={"SPAWN_PROBE": "yes"}, log=log)
|
||||||
|
assert proc.wait(timeout=20) == 0
|
||||||
|
assert out.read_text().split() == ["yes", "False"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("detach", [False, True])
|
||||||
|
def test_spawn_detach_gives_the_child_its_own_session(tmp_path: Path, *, detach: bool) -> None:
|
||||||
|
out = tmp_path / "sid.log"
|
||||||
|
with out.open("wb") as log:
|
||||||
|
proc = procs.spawn(
|
||||||
|
[sys.executable, "-c", "import os; print(os.getsid(0), os.getpid())"], log=log, detach=detach
|
||||||
|
)
|
||||||
|
assert proc.wait(timeout=20) == 0
|
||||||
|
sid, pid = (int(x) for x in out.read_text().split())
|
||||||
|
assert (sid == pid) is detach
|
||||||
|
assert (sid == os.getsid(0)) is (not detach)
|
||||||
139
game_recording/game_recording/tests/test_record.py
Normal file
139
game_recording/game_recording/tests/test_record.py
Normal file
@ -0,0 +1,139 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""The CLI: each subcommand reaches the right module with the right arguments."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from game_recording import cli, finalize, library, supervise
|
||||||
|
from game_recording.options import RunOptions
|
||||||
|
from game_recording.tests.test_helpers import CONFIG
|
||||||
|
|
||||||
|
DOC = {
|
||||||
|
"session": "s1",
|
||||||
|
"tag": "v02",
|
||||||
|
"video": {"start_s": 0.0, "duration_s": 10.0, "end_s": 10.0, "file": "s1.mkv"},
|
||||||
|
"sync": {"approx": False},
|
||||||
|
"events": [{"t": 1.0, "label": "pause_open"}],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def rec_dir(tmp_path: Path) -> Path:
|
||||||
|
(tmp_path / "s1.events.json").write_text(json.dumps(DOC), encoding="utf-8")
|
||||||
|
return tmp_path
|
||||||
|
|
||||||
|
|
||||||
|
def run_cli(capsys: pytest.CaptureFixture[str], *argv: str) -> tuple[int, str]:
|
||||||
|
code = cli.main(list(argv), CONFIG)
|
||||||
|
return code, capsys.readouterr().out
|
||||||
|
|
||||||
|
|
||||||
|
def test_wrap_passes_the_command_after_the_double_dash_and_the_options(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||||
|
) -> None:
|
||||||
|
calls: list[tuple[Any, ...]] = []
|
||||||
|
|
||||||
|
def fake_run(command: list[str], config: object, options: RunOptions) -> int:
|
||||||
|
calls.append((command, config, options))
|
||||||
|
return 4
|
||||||
|
|
||||||
|
monkeypatch.setattr(supervise, "run", fake_run)
|
||||||
|
code, _ = run_cli(capsys, "wrap", "--force", "--fps", "60", "--max-seconds", "2", "--", "godot", "--dev")
|
||||||
|
assert code == 4
|
||||||
|
assert calls == [
|
||||||
|
(["godot", "--dev"], CONFIG, RunOptions(force=True, session="", audio="default", fps=60, max_seconds=2.0))
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_wrap_without_a_double_dash_takes_the_command_as_given(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||||
|
) -> None:
|
||||||
|
calls: list[tuple[list[str], RunOptions]] = []
|
||||||
|
|
||||||
|
def fake_run(command: list[str], config: object, options: RunOptions) -> int:
|
||||||
|
calls.append((command, options))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
monkeypatch.setattr(supervise, "run", fake_run)
|
||||||
|
run_cli(capsys, "wrap", "--session", "x", "--audio", "lavfi", "game")
|
||||||
|
assert calls[0][0] == ["game"]
|
||||||
|
assert calls[0][1].session == "x"
|
||||||
|
assert calls[0][1].audio == "lavfi"
|
||||||
|
|
||||||
|
|
||||||
|
def test_finalize_rebuilds_the_events_of_one_rec_json(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||||
|
) -> None:
|
||||||
|
calls: list[tuple[Path, object]] = []
|
||||||
|
monkeypatch.setattr(finalize, "finalize", lambda meta, moment_map: calls.append((meta, moment_map)))
|
||||||
|
assert run_cli(capsys, "finalize", "/r/s1.rec.json")[0] == 0
|
||||||
|
assert calls == [(Path("/r/s1.rec.json"), CONFIG.moments)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_prints_the_library(rec_dir: Path, capsys: pytest.CaptureFixture[str]) -> None:
|
||||||
|
assert run_cli(capsys, "list", "--dir", str(rec_dir)) == (0, "s1 00:10.000 1 moments v02\n")
|
||||||
|
|
||||||
|
|
||||||
|
def test_latest_prints_the_moments_of_the_session(rec_dir: Path, capsys: pytest.CaptureFixture[str]) -> None:
|
||||||
|
code, out = run_cli(capsys, "latest", "--dir", str(rec_dir), "--session", "s1")
|
||||||
|
assert code == 0
|
||||||
|
assert "pause_open" in out
|
||||||
|
|
||||||
|
|
||||||
|
def test_open_dry_run_prints_the_player_command(rec_dir: Path, capsys: pytest.CaptureFixture[str]) -> None:
|
||||||
|
code, out = run_cli(capsys, "open", "1", "--dir", str(rec_dir), "--dry-run")
|
||||||
|
assert code == 0
|
||||||
|
assert out.startswith("mpv ")
|
||||||
|
assert out.strip().endswith("s1.mkv")
|
||||||
|
|
||||||
|
|
||||||
|
def test_open_without_dry_run_reaches_the_player(
|
||||||
|
rec_dir: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||||
|
) -> None:
|
||||||
|
seen: list[tuple[int | None, bool]] = []
|
||||||
|
|
||||||
|
def fake_open(doc: object, directory: Path, n: int | None, *, dry_run: bool) -> int:
|
||||||
|
seen.append((n, dry_run))
|
||||||
|
return 3
|
||||||
|
|
||||||
|
monkeypatch.setattr(library, "open_moment", fake_open)
|
||||||
|
assert run_cli(capsys, "open", "--dir", str(rec_dir))[0] == 3
|
||||||
|
assert seen == [(None, False)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_open_of_a_missing_moment_exits_with_the_message(rec_dir: Path, capsys: pytest.CaptureFixture[str]) -> None:
|
||||||
|
with pytest.raises(SystemExit) as raised:
|
||||||
|
run_cli(capsys, "open", "9", "--dir", str(rec_dir), "--dry-run")
|
||||||
|
assert str(raised.value) == "no moment 9 (1..1)"
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_session_that_matches_nothing_exits_with_the_message(
|
||||||
|
rec_dir: Path, capsys: pytest.CaptureFixture[str]
|
||||||
|
) -> None:
|
||||||
|
with pytest.raises(SystemExit) as raised:
|
||||||
|
run_cli(capsys, "latest", "--dir", str(rec_dir), "--session", "zzz")
|
||||||
|
assert str(raised.value) == f"no recordings in {rec_dir}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_default_dir_is_the_feedback_recordings_folder(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
monkeypatch.setenv("DEMO_BINARIES", "/b")
|
||||||
|
assert cli.default_dir(CONFIG) == Path("/b/feedback/recordings")
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_without_dir_uses_the_default_folder(
|
||||||
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
|
||||||
|
) -> None:
|
||||||
|
rec = tmp_path / "feedback" / "recordings"
|
||||||
|
rec.mkdir(parents=True)
|
||||||
|
(rec / "s1.events.json").write_text(json.dumps(DOC), encoding="utf-8")
|
||||||
|
monkeypatch.setenv("DEMO_BINARIES", str(tmp_path))
|
||||||
|
assert run_cli(capsys, "list") == (0, "s1 00:10.000 1 moments v02\n")
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_missing_subcommand_is_a_usage_error() -> None:
|
||||||
|
with pytest.raises(SystemExit) as raised:
|
||||||
|
cli.main([], CONFIG)
|
||||||
|
assert raised.value.code == 2
|
||||||
234
game_recording/game_recording/tests/test_recorder.py
Normal file
234
game_recording/game_recording/tests/test_recorder.py
Normal file
@ -0,0 +1,234 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""The launcher's Recorder: backend choice, fallback to x11grab, the t0 of a gsr part, 30 fps."""
|
||||||
|
|
||||||
|
from collections.abc import Callable, Iterator
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import signal
|
||||||
|
import stat
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from game_recording import gsr, procs, recorder, window
|
||||||
|
from game_recording.options import DEFAULT_FPS, RecorderOptions
|
||||||
|
from game_recording.supervise import recording_paths
|
||||||
|
|
||||||
|
FAKE_GSR = """#!{python}
|
||||||
|
import os, pathlib, signal, sys, time
|
||||||
|
args = sys.argv[1:]
|
||||||
|
out = args[args.index("-o") + 1]
|
||||||
|
mode = os.environ.get("FAKE_GSR", "ok")
|
||||||
|
if mode == "die":
|
||||||
|
sys.exit(1)
|
||||||
|
if mode == "ok":
|
||||||
|
pathlib.Path(out + ".ts").write_text("monotonic_microsec\\trealtime_microsec\\n5\\t1800000007250000\\n")
|
||||||
|
signal.signal(signal.SIGINT, lambda *_: sys.exit(0))
|
||||||
|
time.sleep(60)
|
||||||
|
"""
|
||||||
|
FAKE_FFMPEG = """#!{python}
|
||||||
|
import signal, sys, time
|
||||||
|
signal.signal(signal.SIGINT, lambda *_: sys.exit(0))
|
||||||
|
time.sleep(60)
|
||||||
|
"""
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
WIN = window.Window(id=0x4200007, width=1280, height=800)
|
||||||
|
GSR_T0 = 1_800_000_007.25 - gsr.CAPTURE_LATENCY_S # FAKE_GSR's first-frame stamp, less the latency
|
||||||
|
|
||||||
|
Make = Callable[[str], recorder.Recorder]
|
||||||
|
|
||||||
|
|
||||||
|
def install_fake(folder: Path, name: str, body: str) -> None:
|
||||||
|
path = folder / name
|
||||||
|
path.write_text(body.format(python=sys.executable), encoding="utf-8")
|
||||||
|
path.chmod(path.stat().st_mode | stat.S_IXUSR)
|
||||||
|
|
||||||
|
|
||||||
|
class Rig:
|
||||||
|
"""A recorder factory over fake gsr and ffmpeg binaries; every recorder it made is stopped at the end."""
|
||||||
|
|
||||||
|
def __init__(self, root: Path) -> None:
|
||||||
|
self.feedback = root / "fb"
|
||||||
|
self.paths = recording_paths(self.feedback, "s1")
|
||||||
|
self.made: list[recorder.Recorder] = []
|
||||||
|
|
||||||
|
def make(self, backend: str) -> recorder.Recorder:
|
||||||
|
opts = RecorderOptions(
|
||||||
|
session="s1", feedback=self.feedback, fps=30, audio="default", nice="0",
|
||||||
|
usable=frozenset({"libx264"}), backend=backend,
|
||||||
|
) # fmt: skip
|
||||||
|
rec = recorder.Recorder(mock.Mock(), self.paths, opts)
|
||||||
|
self.made.append(rec)
|
||||||
|
return rec
|
||||||
|
|
||||||
|
def meta(self) -> dict[str, object]:
|
||||||
|
data: dict[str, object] = json.loads(self.paths["meta"].read_text(encoding="utf-8"))
|
||||||
|
return data
|
||||||
|
|
||||||
|
def running_gsr(self) -> recorder.Recorder:
|
||||||
|
rec = self.make("gsr")
|
||||||
|
rec._start_part(WIN)
|
||||||
|
return rec
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def rig(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Rig]:
|
||||||
|
bin_dir = tmp_path / "bin"
|
||||||
|
bin_dir.mkdir()
|
||||||
|
install_fake(bin_dir, "gpu-screen-recorder", FAKE_GSR)
|
||||||
|
install_fake(bin_dir, "ffmpeg", FAKE_FFMPEG)
|
||||||
|
monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}{os.environ['PATH']}")
|
||||||
|
monkeypatch.setenv("DISPLAY", ":9")
|
||||||
|
monkeypatch.setenv("FAKE_GSR", "ok")
|
||||||
|
made = Rig(tmp_path)
|
||||||
|
yield made
|
||||||
|
for rec in made.made:
|
||||||
|
if rec.proc is not None and rec.proc.poll() is None:
|
||||||
|
rec.proc.send_signal(signal.SIGKILL)
|
||||||
|
rec.proc.wait()
|
||||||
|
|
||||||
|
|
||||||
|
def stop_quietly(rec: recorder.Recorder) -> None:
|
||||||
|
"""Stops the recorder with the alignment (ffprobe on a fake file) faked out."""
|
||||||
|
with mock.patch.object(gsr, "align"):
|
||||||
|
rec.stop()
|
||||||
|
|
||||||
|
|
||||||
|
def test_defaults_are_30_fps() -> None:
|
||||||
|
assert DEFAULT_FPS == 30
|
||||||
|
|
||||||
|
|
||||||
|
def test_gsr_part_puts_t0_on_its_first_frame(rig: Rig) -> None:
|
||||||
|
rec = rig.running_gsr()
|
||||||
|
stop_quietly(rec)
|
||||||
|
assert rec.backend == "gsr"
|
||||||
|
assert rec.t0 == pytest.approx(GSR_T0, abs=1e-6)
|
||||||
|
meta = rig.meta()
|
||||||
|
assert meta["t0_unix"] == pytest.approx(GSR_T0, abs=1e-6)
|
||||||
|
assert meta["backend"] == "gsr"
|
||||||
|
assert meta["parts"] == ["s1.mkv"]
|
||||||
|
assert meta["fps"] == 30
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_gsr_that_fails_at_start_falls_back_to_x11grab_with_a_fresh_t0(
|
||||||
|
rig: Rig, monkeypatch: pytest.MonkeyPatch
|
||||||
|
) -> None:
|
||||||
|
monkeypatch.setenv("FAKE_GSR", "die")
|
||||||
|
rec = rig.make("gsr")
|
||||||
|
before = time.time()
|
||||||
|
rec._start_part(WIN)
|
||||||
|
stop_quietly(rec)
|
||||||
|
assert rec.backend == "x11grab"
|
||||||
|
assert rec.t0 >= before
|
||||||
|
assert rec.t0 < time.time() + 1
|
||||||
|
meta = rig.meta()
|
||||||
|
assert meta["backend"] == "x11grab"
|
||||||
|
assert meta["parts"] == ["s1.mkv"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_gsr_keeps_recording_while_its_window_is_shown(rig: Rig) -> None:
|
||||||
|
rec = rig.running_gsr()
|
||||||
|
proc = rec.proc
|
||||||
|
with mock.patch.object(window, "largest", return_value=WIN):
|
||||||
|
assert rec.step()
|
||||||
|
assert rec.proc is proc
|
||||||
|
stop_quietly(rec)
|
||||||
|
|
||||||
|
|
||||||
|
def test_gsr_part_ends_when_its_window_is_hidden_so_a_new_part_follows(rig: Rig) -> None:
|
||||||
|
# gsr neither exits nor resumes after an unmap (bench.sh gap on :0): the recorder ends the part itself
|
||||||
|
rec = rig.running_gsr()
|
||||||
|
proc = rec.proc
|
||||||
|
assert proc is not None
|
||||||
|
with (
|
||||||
|
mock.patch.object(window, "largest", return_value=None),
|
||||||
|
mock.patch.object(window, "wait_stable", return_value=None),
|
||||||
|
):
|
||||||
|
assert not rec.step()
|
||||||
|
assert proc.poll() is not None, "the hidden window's gsr was stopped"
|
||||||
|
assert rec.proc is None
|
||||||
|
assert len(rec.gsr.pending) == 1
|
||||||
|
stop_quietly(rec)
|
||||||
|
|
||||||
|
|
||||||
|
def test_x11grab_backend_never_starts_gsr(rig: Rig) -> None:
|
||||||
|
rec = rig.make("x11grab")
|
||||||
|
with mock.patch.object(gsr, "start") as started:
|
||||||
|
rec._start_part(WIN)
|
||||||
|
started.assert_not_called()
|
||||||
|
assert rig.meta()["backend"] == "x11grab"
|
||||||
|
stop_quietly(rec)
|
||||||
|
|
||||||
|
|
||||||
|
def test_stopping_a_gsr_part_aligns_a_later_part_to_the_t0_timeline(rig: Rig) -> None:
|
||||||
|
rec = rig.make("gsr")
|
||||||
|
rec.t0 = GSR_T0 - 10.0
|
||||||
|
rec.parts = ["s1.mkv"] # a second part: its first frame is 10 s after t0
|
||||||
|
with mock.patch.object(gsr, "align") as align:
|
||||||
|
rec._start_part(WIN)
|
||||||
|
rec.stop()
|
||||||
|
align.assert_called_once_with(rig.paths["dir"] / "s1.part2.mkv", first_unix=GSR_T0, t0=GSR_T0 - 10.0)
|
||||||
|
assert rec.t0 == GSR_T0 - 10.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_part_that_ended_during_play_is_aligned_only_after_the_game_exits(rig: Rig) -> None:
|
||||||
|
rec = rig.make("gsr")
|
||||||
|
with mock.patch.object(gsr, "align") as align:
|
||||||
|
rec._start_part(WIN)
|
||||||
|
assert rec.proc is not None
|
||||||
|
rec.proc.send_signal(signal.SIGINT)
|
||||||
|
rec.proc.wait(timeout=5)
|
||||||
|
rec.close_part() # the window went away; the game still runs
|
||||||
|
align.assert_not_called()
|
||||||
|
rec.stop() # the game exited
|
||||||
|
align.assert_called_once()
|
||||||
|
|
||||||
|
|
||||||
|
def test_every_pending_part_is_aligned_once_and_its_first_frame_is_in_rec_json(rig: Rig) -> None:
|
||||||
|
rec = rig.make("gsr")
|
||||||
|
with mock.patch.object(gsr, "align") as align:
|
||||||
|
for _ in range(2):
|
||||||
|
rec._start_part(WIN)
|
||||||
|
assert rec.proc is not None
|
||||||
|
rec.proc.send_signal(signal.SIGINT)
|
||||||
|
rec.proc.wait(timeout=5)
|
||||||
|
rec.close_part()
|
||||||
|
rec.stop()
|
||||||
|
assert align.call_count == 2
|
||||||
|
assert rig.meta()["first_frame_unix"] == {"s1.mkv": GSR_T0, "s1.part2.mkv": GSR_T0}
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_dead_proc_still_closes_once(rig: Rig) -> None:
|
||||||
|
rec = rig.make("gsr")
|
||||||
|
with mock.patch.object(gsr, "align") as align:
|
||||||
|
rec._start_part(WIN)
|
||||||
|
rec.stop()
|
||||||
|
rec.stop()
|
||||||
|
assert align.call_count == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_stop_recorder_returns_true_for_an_already_ended_process() -> None:
|
||||||
|
done = procs.spawn([sys.executable, "-c", "pass"])
|
||||||
|
done.wait(timeout=20)
|
||||||
|
assert recorder.stop_recorder(done)
|
||||||
|
|
||||||
|
|
||||||
|
def test_stop_recorder_interrupts_a_running_process_and_reports_a_clean_finish() -> None:
|
||||||
|
code = "import signal, sys, time; signal.signal(signal.SIGINT, lambda *_: sys.exit(0)); time.sleep(60)"
|
||||||
|
proc = procs.spawn([sys.executable, "-c", code])
|
||||||
|
time.sleep(0.5) # let the child install its handler
|
||||||
|
assert recorder.stop_recorder(proc, grace_s=10.0)
|
||||||
|
assert proc.returncode == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_stop_recorder_kills_a_process_that_ignores_sigint() -> None:
|
||||||
|
code = "import signal, time; signal.signal(signal.SIGINT, signal.SIG_IGN); time.sleep(60)"
|
||||||
|
proc = procs.spawn([sys.executable, "-c", code])
|
||||||
|
time.sleep(0.5)
|
||||||
|
assert not recorder.stop_recorder(proc, grace_s=0.2)
|
||||||
|
assert proc.returncode == -signal.SIGKILL
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user