testsAndMisc/python_pkg/phone_lease/ops.py
Krzysztof kuhy Rudnicki 24503e9197
Some checks are pending
md-naming / markdown naming convention (push) Waiting to run
Pre-commit checks / pre-commit (${{ matrix.group }}) (mypy, mypy) (push) Waiting to run
Pre-commit checks / pre-commit (${{ matrix.group }}) (pylint, pylint) (push) Waiting to run
Pre-commit checks / pre-commit (${{ matrix.group }}) (rest, ) (push) Waiting to run
Pre-commit checks / pre-commit (${{ matrix.group }}) (shellcheck, shellcheck) (push) Waiting to run
Python tests / test (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Shell tests / shell-tests (push) Waiting to run
Shell tests / lib-tests (push) Waiting to run
Shell tests / arch-tests (push) Waiting to run
phone_lease: fair FIFO queue; drop fix_waifu2x
Finish the queue left uncommitted on 2026-11-17: callers that find a
scope taken get a ticket and are granted in arrival order, dead
sessions are reaped at once. The CLI keeps exit 3 for a held scope.
fix_waifu2x.sh patched the CUDA waifu2x build, now uninstalled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWV2U9cEtTMTf7iQWin
2026-11-21 11:50:32 +01:00

114 lines
3.4 KiB
Python

"""Release, status, the ``holds`` check the adb hook asks, and the reaper."""
from __future__ import annotations
import time
from typing import TYPE_CHECKING
from python_pkg.phone_lease import _cleanup, _queue
from python_pkg.phone_lease.lease import (
SCREEN,
WHOLE_PHONE,
Clock,
Lease,
Ticket,
lease_paths,
locked_update,
read_book,
read_leases,
)
from python_pkg.phone_lease.owner import owner_id
if TYPE_CHECKING:
from collections.abc import Callable
# Longest the reaper sleeps between looks at the lease file.
REAP_POLL = 5.0
def release(
serial: str, *, scope: str = f"pkg:{SCREEN}", owner: str | None = None
) -> bool:
"""Drop ``owner``'s lease and ticket on ``scope``, running the lease's cleanup.
True if anything was dropped.
"""
me = owner_id() if owner is None else owner
dropped, found = locked_update(
serial, lambda book, _now: _queue.leave(book, me, scope), time.time()
)
for lease in dropped:
_cleanup.run(lease.cleanup)
return found
def status_all(serial: str, now: float | None = None) -> list[Lease]:
"""Every live lease on ``serial`` (read-only: no cleanup runs here)."""
at = time.time() if now is None else now
return [x for x in read_leases(lease_paths(serial)[1]) if not x.is_expired(at)]
def queue_of(serial: str) -> list[Ticket]:
"""The tickets in ``serial``'s file, first in line first (read-only).
Stale tickets stay listed until the next locked update tidies them out.
"""
tickets = read_book(lease_paths(serial)[1]).tickets
return sorted(tickets, key=lambda x: x.number)
def status(
serial: str, now: float | None = None, *, scope: str = f"pkg:{SCREEN}"
) -> Lease | None:
"""The live lease on ``scope``, or None when free."""
return next((x for x in status_all(serial, now) if x.scope == scope), None)
def holds(
serial: str, owner: str, scope: str = f"pkg:{SCREEN}", now: float | None = None
) -> bool:
"""Whether ``owner`` may act on ``scope`` right now.
True when it holds that scope or the whole phone. This is the question
the raw-adb hook asks before letting an ``input``/``am`` through.
"""
return any(
x.owner == owner and x.scope in {scope, WHOLE_PHONE}
for x in status_all(serial, now)
)
def reap(
serial: str,
owner: str,
scope: str,
*,
clock: Clock | None = None,
alive: Callable[[], bool] = lambda: True,
) -> bool:
"""Wait until ``owner``'s lease on ``scope`` ends; run its cleanup if it expired.
Refreshes push the expiry out, so this re-reads the file after every
sleep. Returns True when it ran the cleanup, False when the holder
released first (``release`` already ran it) or ``alive`` says stop.
"""
clock = clock or Clock()
while alive():
lease = next(
(
x
for x in read_leases(lease_paths(serial)[1])
if (x.owner, x.scope) == (owner, scope)
),
None,
)
if lease is None:
return False
if lease.is_expired(clock.now()):
# locked_update drops expired leases and runs their cleanup itself.
locked_update(serial, lambda _book, _now: None, clock.now())
return True
# Wake at least every few seconds so a released lease frees the reaper.
clock.sleep(min(REAP_POLL, max(0.5, lease.expires - clock.now())))
return False