|
| 1 | +"""Lock the workstation, wait for it to be unlocked, and classify transitions. |
| 2 | +
|
| 3 | +:mod:`session_guard` answers "is the session locked right now?" and raises if it |
| 4 | +is. The missing half is *acting* on the lock state: lock the machine at the end |
| 5 | +of an unattended run, block until a human unlocks it before resuming, or reduce |
| 6 | +a stream of lock-state samples to lock / unlock events. ``lock_session`` adds: |
| 7 | +
|
| 8 | +* :func:`lock_session` — lock the workstation now (``LockWorkStation`` on |
| 9 | + Windows, ``loginctl lock-session`` / ``CGSession -suspend`` elsewhere), |
| 10 | + through an injectable ``driver`` seam. |
| 11 | +* :func:`plan_lock_session` — pure planner describing how the lock would be |
| 12 | + performed on this OS, and whether a default is available. |
| 13 | +* :func:`wait_for_unlock` / :func:`wait_for_lock` — poll |
| 14 | + :func:`session_guard.is_session_locked` until the state flips or a timeout, |
| 15 | + with injectable ``clock`` / ``sleep`` / ``probe`` for deterministic tests. |
| 16 | +* :func:`classify_lock_transitions` — pure: a list of lock-state samples to a |
| 17 | + list of ``{event, locked}`` lock / unlock transitions. |
| 18 | +
|
| 19 | +Imports no ``PySide6``. |
| 20 | +""" |
| 21 | +import sys |
| 22 | +import time |
| 23 | +from typing import Any, Callable, Dict, List, Optional, Sequence |
| 24 | + |
| 25 | +from je_auto_control.utils.session_guard import is_session_locked |
| 26 | +from je_auto_control.utils.session_guard.session_guard import LockProbe |
| 27 | + |
| 28 | +# A driver performs the lock and returns whether it succeeded. |
| 29 | +LockDriver = Callable[[], bool] |
| 30 | + |
| 31 | + |
| 32 | +def _win_lock() -> bool: |
| 33 | + """Lock the Windows workstation via ``LockWorkStation``.""" |
| 34 | + import ctypes |
| 35 | + user32 = ctypes.windll.user32 # nosec B607 # reason: fixed system DLL |
| 36 | + return bool(user32.LockWorkStation()) |
| 37 | + |
| 38 | + |
| 39 | +def _lock_backend() -> str: |
| 40 | + """Return the lock backend name for the current platform.""" |
| 41 | + if sys.platform.startswith("win"): |
| 42 | + return "LockWorkStation" |
| 43 | + if sys.platform == "darwin": |
| 44 | + return "CGSession" |
| 45 | + return "loginctl" |
| 46 | + |
| 47 | + |
| 48 | +_CGSESSION = ("/System/Library/CoreServices/Menu Extras/" |
| 49 | + "User.menu/Contents/Resources/CGSession") |
| 50 | + |
| 51 | + |
| 52 | +def _lock_argv(backend: str) -> Optional[List[str]]: |
| 53 | + """Return the fixed argv for a subprocess lock backend, or None.""" |
| 54 | + if backend == "loginctl": |
| 55 | + return ["loginctl", "lock-session"] |
| 56 | + if backend == "CGSession": |
| 57 | + return [_CGSESSION, "-suspend"] |
| 58 | + return None |
| 59 | + |
| 60 | + |
| 61 | +def plan_lock_session() -> Dict[str, Any]: |
| 62 | + """Describe how the workstation would be locked on this OS (pure). |
| 63 | +
|
| 64 | + Returns ``{backend, argv, available}``. ``available`` is ``True`` when this |
| 65 | + platform has a built-in default; otherwise :func:`lock_session` needs an |
| 66 | + explicit ``driver=``. |
| 67 | + """ |
| 68 | + backend = _lock_backend() |
| 69 | + argv = _lock_argv(backend) |
| 70 | + available = backend == "LockWorkStation" or argv is not None |
| 71 | + return {"backend": backend, "argv": argv, "available": available} |
| 72 | + |
| 73 | + |
| 74 | +def _run_argv(argv: List[str]) -> bool: |
| 75 | + """Run a fixed lock argv and report success (no shell).""" |
| 76 | + import subprocess # nosec B404 # reason: fixed argv, no shell |
| 77 | + completed = subprocess.run(argv, check=False) # nosec B603 # nosemgrep |
| 78 | + return completed.returncode == 0 |
| 79 | + |
| 80 | + |
| 81 | +def _default_driver() -> LockDriver: |
| 82 | + """Return the OS lock driver, or raise if none is available.""" |
| 83 | + backend = _lock_backend() |
| 84 | + if backend == "LockWorkStation": |
| 85 | + return _win_lock |
| 86 | + argv = _lock_argv(backend) |
| 87 | + if argv is not None: |
| 88 | + return lambda: _run_argv(argv) |
| 89 | + raise RuntimeError( |
| 90 | + "lock_session has no OS driver on this platform; pass driver=") |
| 91 | + |
| 92 | + |
| 93 | +def lock_session(*, driver: Optional[LockDriver] = None) -> bool: |
| 94 | + """Lock the workstation now; return whether the lock was requested. |
| 95 | +
|
| 96 | + Pass ``driver`` (a ``() -> bool``) to intercept the OS call in tests; the |
| 97 | + default locks via the platform backend from :func:`plan_lock_session`. |
| 98 | + """ |
| 99 | + acquire = driver if driver is not None else _default_driver() |
| 100 | + return bool(acquire()) |
| 101 | + |
| 102 | + |
| 103 | +def _wait_lock_state(target_locked: bool, *, probe: Optional[LockProbe], |
| 104 | + timeout_s: float, interval_s: float, |
| 105 | + clock: Callable[[], float], |
| 106 | + sleep: Callable[[float], None]) -> bool: |
| 107 | + """Poll until the lock state equals ``target_locked`` or timeout.""" |
| 108 | + deadline = clock() + float(timeout_s) |
| 109 | + while True: |
| 110 | + if bool(is_session_locked(probe)) == target_locked: |
| 111 | + return True |
| 112 | + if clock() >= deadline: |
| 113 | + return False |
| 114 | + sleep(float(interval_s)) |
| 115 | + |
| 116 | + |
| 117 | +def wait_for_unlock(*, probe: Optional[LockProbe] = None, |
| 118 | + timeout_s: float = 30.0, interval_s: float = 0.5, |
| 119 | + clock: Callable[[], float] = time.monotonic, |
| 120 | + sleep: Callable[[float], None] = time.sleep) -> bool: |
| 121 | + """Block until the session is unlocked; return ``True``, or ``False`` on timeout. |
| 122 | +
|
| 123 | + Reuses :func:`session_guard.is_session_locked` (Windows default probe). |
| 124 | + ``clock`` / ``sleep`` / ``probe`` are injectable for deterministic tests. |
| 125 | + """ |
| 126 | + return _wait_lock_state(False, probe=probe, timeout_s=timeout_s, |
| 127 | + interval_s=interval_s, clock=clock, sleep=sleep) |
| 128 | + |
| 129 | + |
| 130 | +def wait_for_lock(*, probe: Optional[LockProbe] = None, |
| 131 | + timeout_s: float = 30.0, interval_s: float = 0.5, |
| 132 | + clock: Callable[[], float] = time.monotonic, |
| 133 | + sleep: Callable[[float], None] = time.sleep) -> bool: |
| 134 | + """Block until the session is locked; return ``True``, or ``False`` on timeout.""" |
| 135 | + return _wait_lock_state(True, probe=probe, timeout_s=timeout_s, |
| 136 | + interval_s=interval_s, clock=clock, sleep=sleep) |
| 137 | + |
| 138 | + |
| 139 | +def classify_lock_transitions(states: Sequence[bool]) -> List[Dict[str, Any]]: |
| 140 | + """Reduce lock-state samples to lock / unlock transitions (pure). |
| 141 | +
|
| 142 | + Each adjacent ``False -> True`` yields a ``lock`` event and each |
| 143 | + ``True -> False`` an ``unlock`` event; unchanged samples yield nothing. |
| 144 | + """ |
| 145 | + events: List[Dict[str, Any]] = [] |
| 146 | + previous: Optional[bool] = None |
| 147 | + for sample in states: |
| 148 | + current = bool(sample) |
| 149 | + if previous is not None and current != previous: |
| 150 | + kind = "lock" if current else "unlock" |
| 151 | + events.append({"event": kind, "locked": current}) |
| 152 | + previous = current |
| 153 | + return events |
0 commit comments