mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-24 07:06:28 +01:00
Compare commits
3 Commits
02659e0abf
...
3589d166cd
| Author | SHA1 | Date | |
|---|---|---|---|
| 3589d166cd | |||
| f5f9db21dc | |||
| 40f94833c1 |
69
crdt-sync/crdt_sync/_autherrors.py
Normal file
69
crdt-sync/crdt_sync/_autherrors.py
Normal file
@ -0,0 +1,69 @@
|
||||
"""Turning a Firebase auth response into a message, and reading its verdict.
|
||||
|
||||
Split from :mod:`crdt_sync._firebase_auth`, which keeps the token provider.
|
||||
identitytoolkit reports failures as a nested JSON error whose useful part is
|
||||
buried; these turn that into something a log line can carry, and decide
|
||||
whether the failure is permanent (the refresh token is dead and the user must
|
||||
sign in again) or worth retrying.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from crdt_sync._remote import RemoteSyncError
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import requests as _requests
|
||||
|
||||
|
||||
class FirebaseAuthError(RemoteSyncError):
|
||||
"""Raised for an authentication failure the caller must not ignore.
|
||||
|
||||
A :class:`crdt_sync.RemoteSyncError` so callers that only care about
|
||||
"sync is broken" can catch one type, while a settings screen can single
|
||||
this out to say "your password is wrong" rather than "the network is
|
||||
down".
|
||||
"""
|
||||
|
||||
def _reason(response: _requests.Response) -> str:
|
||||
"""Return Google's machine-readable error reason, in parentheses.
|
||||
|
||||
Pulls ``INVALID_PASSWORD`` / ``TOKEN_EXPIRED`` / ``USER_DISABLED`` out of
|
||||
the body so the raised message says what actually went wrong rather than
|
||||
just reporting a status code.
|
||||
"""
|
||||
try:
|
||||
data = response.json()
|
||||
except ValueError:
|
||||
# A non-JSON body (a proxy error page, say): the status code is all
|
||||
# the detail there is.
|
||||
return ""
|
||||
if not isinstance(data, dict):
|
||||
return ""
|
||||
error = data.get("error")
|
||||
if isinstance(error, dict):
|
||||
return f" ({error.get('message')})"
|
||||
if isinstance(error, str):
|
||||
return f" ({error})"
|
||||
return ""
|
||||
|
||||
|
||||
#: Reasons that mean the refresh token is permanently dead. Only these clear
|
||||
#: the session: a network error or a 5xx must not, because a device that signs
|
||||
#: itself out whenever the wifi drops needs a manual sign-in to recover, which
|
||||
#: is a worse failure than the stale banner this guards against.
|
||||
_TERMINAL_AUTH_REASONS = (
|
||||
"TOKEN_EXPIRED",
|
||||
"USER_DISABLED",
|
||||
"USER_NOT_FOUND",
|
||||
"INVALID_REFRESH_TOKEN",
|
||||
"INVALID_GRANT_TYPE",
|
||||
"MISSING_REFRESH_TOKEN",
|
||||
)
|
||||
|
||||
|
||||
def _is_revoked(error: FirebaseAuthError) -> bool:
|
||||
"""Return whether ``error`` means the refresh token is permanently dead."""
|
||||
message = str(error)
|
||||
return any(reason in message for reason in _TERMINAL_AUTH_REASONS)
|
||||
146
crdt-sync/crdt_sync/_credentials.py
Normal file
146
crdt-sync/crdt_sync/_credentials.py
Normal file
@ -0,0 +1,146 @@
|
||||
"""Firebase credentials and the stores that persist them.
|
||||
|
||||
Split from :mod:`crdt_sync._firebase_auth`, which keeps the token provider.
|
||||
A credential set is an ID token, a refresh token and an expiry; the stores
|
||||
decide where it survives a restart -- memory for tests, a mode-0600 file for
|
||||
real installs.
|
||||
|
||||
Re-exported from :mod:`crdt_sync._firebase_auth`, so existing imports work.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import datetime as dt
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Protocol
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# Refresh this long before the token actually expires. An ID token lives ~1h;
|
||||
# refreshing early means a tick that starts just under the wire still finishes
|
||||
# with a valid token rather than 401ing halfway through a multi-file push.
|
||||
_REFRESH_SKEW = dt.timedelta(minutes=5)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FirebaseCredentials:
|
||||
"""One device's session: a short-lived ID token plus its refresh token.
|
||||
|
||||
Attributes:
|
||||
----------
|
||||
id_token:
|
||||
The bearer credential for Realtime Database requests. Expires fast.
|
||||
refresh_token:
|
||||
The long-lived credential. **This is the secret worth protecting.**
|
||||
expires_at:
|
||||
When ``id_token`` stops being accepted, in UTC.
|
||||
"""
|
||||
|
||||
id_token: str
|
||||
refresh_token: str
|
||||
expires_at: dt.datetime
|
||||
|
||||
def is_expired_at(self, now: dt.datetime) -> bool:
|
||||
"""Return whether the token is expired, or close enough to it."""
|
||||
return now + _REFRESH_SKEW >= self.expires_at
|
||||
|
||||
def to_json(self) -> dict[str, str]:
|
||||
"""Return a JSON-serializable form."""
|
||||
return {
|
||||
"id_token": self.id_token,
|
||||
"refresh_token": self.refresh_token,
|
||||
"expires_at": self.expires_at.isoformat(),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, data: dict[str, str]) -> FirebaseCredentials:
|
||||
"""Rebuild credentials from :meth:`to_json` output."""
|
||||
return cls(
|
||||
id_token=data["id_token"],
|
||||
refresh_token=data["refresh_token"],
|
||||
expires_at=dt.datetime.fromisoformat(data["expires_at"]),
|
||||
)
|
||||
|
||||
|
||||
class CredentialStore(Protocol):
|
||||
"""Where a device keeps its credentials between runs."""
|
||||
|
||||
def load(self) -> FirebaseCredentials | None:
|
||||
"""Return the stored credentials, or ``None`` if not signed in."""
|
||||
|
||||
def save(self, credentials: FirebaseCredentials) -> None:
|
||||
"""Persist ``credentials``."""
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Forget any stored credentials."""
|
||||
|
||||
|
||||
class MemoryCredentialStore:
|
||||
"""A :class:`CredentialStore` for tests and one-shot scripts."""
|
||||
|
||||
def __init__(self, credentials: FirebaseCredentials | None = None) -> None:
|
||||
"""Start holding ``credentials`` (or nothing)."""
|
||||
self._credentials = credentials
|
||||
|
||||
def load(self) -> FirebaseCredentials | None:
|
||||
"""Return the held credentials."""
|
||||
return self._credentials
|
||||
|
||||
def save(self, credentials: FirebaseCredentials) -> None:
|
||||
"""Replace the held credentials."""
|
||||
self._credentials = credentials
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Drop the held credentials."""
|
||||
self._credentials = None
|
||||
|
||||
|
||||
class FileCredentialStore:
|
||||
"""A :class:`CredentialStore` backed by a ``0600`` JSON file.
|
||||
|
||||
Persistence is not an optimisation here: ``wake_alarm``'s PC side is a
|
||||
fresh process every minute and ``diet_guard``'s every 15 minutes, so an
|
||||
in-memory store would re-authenticate thousands of times a day.
|
||||
"""
|
||||
|
||||
def __init__(self, path: Path) -> None:
|
||||
"""Store credentials at ``path``, creating parent dirs as needed."""
|
||||
self._path = path
|
||||
|
||||
def load(self) -> FirebaseCredentials | None:
|
||||
"""Return the stored credentials, or ``None`` if the file is absent.
|
||||
|
||||
A corrupt or truncated file (an interrupted write) reads as "not
|
||||
signed in" rather than raising: the caller's next step is to sign in
|
||||
again, which repairs it.
|
||||
"""
|
||||
try:
|
||||
data = json.loads(self._path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
try:
|
||||
return FirebaseCredentials.from_json(data)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None
|
||||
|
||||
def save(self, credentials: FirebaseCredentials) -> None:
|
||||
"""Write ``credentials`` atomically, readable only by this user."""
|
||||
self._path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temp = self._path.with_suffix(f"{self._path.suffix}.tmp")
|
||||
# Create with 0600 from the outset -- writing then chmod'ing would
|
||||
# leave the refresh token world-readable for the gap in between.
|
||||
temp.touch(mode=0o600)
|
||||
temp.write_text(json.dumps(credentials.to_json()), encoding="utf-8")
|
||||
temp.replace(self._path)
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Delete the credentials file if it exists."""
|
||||
self._path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _utcnow() -> dt.datetime:
|
||||
return dt.datetime.now(dt.timezone.utc)
|
||||
100
crdt-sync/crdt_sync/_fbkeys.py
Normal file
100
crdt-sync/crdt_sync/_fbkeys.py
Normal file
@ -0,0 +1,100 @@
|
||||
"""Escaping arbitrary strings into Firebase Realtime Database keys.
|
||||
|
||||
Split from :mod:`crdt_sync._firebase`, which keeps the client. RTDB forbids
|
||||
``.``, ``$``, ``#``, ``[``, ``]`` and ``/`` in a key, but the app stores
|
||||
record ids and file paths that contain them, so every key is escaped on the
|
||||
way in and unescaped on the way out. The pair has to round-trip exactly or a
|
||||
device silently stops seeing its own writes.
|
||||
|
||||
Re-exported from :mod:`crdt_sync._firebase`, so existing imports keep working.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
# Characters Realtime Database forbids in a key, plus ``~`` itself because it
|
||||
# is this module's escape character. ``/`` is absent deliberately: it is the
|
||||
# path separator, handled by splitting into segments before escaping.
|
||||
_ESCAPES = {
|
||||
"~": "~7E",
|
||||
".": "~2E",
|
||||
"$": "~24",
|
||||
"#": "~23",
|
||||
"[": "~5B",
|
||||
"]": "~5D",
|
||||
}
|
||||
_UNESCAPES = {escape: char for char, escape in _ESCAPES.items()}
|
||||
_ESCAPE_LENGTH = 3
|
||||
|
||||
|
||||
def encode_key(segment: str) -> str:
|
||||
"""Escape one path segment into a legal Realtime Database key.
|
||||
|
||||
RTDB rejects ``. $ # [ ] /`` in keys, and the REST API's trailing
|
||||
``.json`` is a *format suffix* rather than part of the path -- so a
|
||||
filename like ``log.json`` cannot be stored verbatim. The mapping is a
|
||||
reversible ``~XX`` escape (``log.json`` -> ``log~2Ejson``) rather than a
|
||||
lossy "strip the extension", because callers see these names again:
|
||||
todo-app lists *filenames*, not device directories, and must keep getting
|
||||
``<uuid>.json`` back.
|
||||
|
||||
``~`` is the escape character because it is legal in RTDB keys and
|
||||
unreserved in URLs, so the escaped form needs no percent-encoding --
|
||||
which the server would otherwise decode back into the illegal character.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
segment : str
|
||||
One path segment, with no ``/`` in it.
|
||||
|
||||
Returns:
|
||||
-------
|
||||
str
|
||||
The escaped key.
|
||||
|
||||
"""
|
||||
return "".join(_ESCAPES.get(char, char) for char in segment)
|
||||
|
||||
|
||||
def decode_key(key: str) -> str:
|
||||
"""Reverse :func:`encode_key`.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
key : str
|
||||
An escaped Realtime Database key.
|
||||
|
||||
Returns:
|
||||
-------
|
||||
str
|
||||
The original segment.
|
||||
|
||||
"""
|
||||
out: list[str] = []
|
||||
index = 0
|
||||
while index < len(key):
|
||||
escape = key[index : index + _ESCAPE_LENGTH]
|
||||
char = _UNESCAPES.get(escape)
|
||||
if char is None:
|
||||
out.append(key[index])
|
||||
index += 1
|
||||
else:
|
||||
out.append(char)
|
||||
index += _ESCAPE_LENGTH
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def encode_path(path: str) -> str:
|
||||
"""Escape every segment of a ``/``-separated logical path.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
path : str
|
||||
A logical path such as ``"todo-sync/notes/abc.json"``.
|
||||
|
||||
Returns:
|
||||
-------
|
||||
str
|
||||
The path with each segment escaped, empty segments dropped.
|
||||
|
||||
"""
|
||||
return "/".join(encode_key(part) for part in path.split("/") if part)
|
||||
@ -19,6 +19,7 @@ from typing import TYPE_CHECKING
|
||||
|
||||
import requests as _requests
|
||||
|
||||
from crdt_sync._fbkeys import decode_key, encode_key, encode_path
|
||||
from crdt_sync._http import new_session
|
||||
from crdt_sync._remote import RemoteNotFoundError, RemoteSyncError
|
||||
|
||||
@ -34,19 +35,6 @@ _DEFAULT_TIMEOUT_SECONDS = 15
|
||||
_HTTP_UNAUTHORIZED = 401
|
||||
_HTTP_FORBIDDEN = 403
|
||||
|
||||
# Characters Realtime Database forbids in a key, plus ``~`` itself because it
|
||||
# is this module's escape character. ``/`` is absent deliberately: it is the
|
||||
# path separator, handled by splitting into segments before escaping.
|
||||
_ESCAPES = {
|
||||
"~": "~7E",
|
||||
".": "~2E",
|
||||
"$": "~24",
|
||||
"#": "~23",
|
||||
"[": "~5B",
|
||||
"]": "~5D",
|
||||
}
|
||||
_UNESCAPES = {escape: char for char, escape in _ESCAPES.items()}
|
||||
_ESCAPE_LENGTH = 3
|
||||
|
||||
|
||||
class FirebaseSyncError(RemoteSyncError):
|
||||
@ -63,80 +51,6 @@ class DatabaseNotFoundError(FirebaseSyncError, RemoteNotFoundError):
|
||||
"""
|
||||
|
||||
|
||||
def encode_key(segment: str) -> str:
|
||||
"""Escape one path segment into a legal Realtime Database key.
|
||||
|
||||
RTDB rejects ``. $ # [ ] /`` in keys, and the REST API's trailing
|
||||
``.json`` is a *format suffix* rather than part of the path -- so a
|
||||
filename like ``log.json`` cannot be stored verbatim. The mapping is a
|
||||
reversible ``~XX`` escape (``log.json`` -> ``log~2Ejson``) rather than a
|
||||
lossy "strip the extension", because callers see these names again:
|
||||
todo-app lists *filenames*, not device directories, and must keep getting
|
||||
``<uuid>.json`` back.
|
||||
|
||||
``~`` is the escape character because it is legal in RTDB keys and
|
||||
unreserved in URLs, so the escaped form needs no percent-encoding --
|
||||
which the server would otherwise decode back into the illegal character.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
segment : str
|
||||
One path segment, with no ``/`` in it.
|
||||
|
||||
Returns:
|
||||
-------
|
||||
str
|
||||
The escaped key.
|
||||
|
||||
"""
|
||||
return "".join(_ESCAPES.get(char, char) for char in segment)
|
||||
|
||||
|
||||
def decode_key(key: str) -> str:
|
||||
"""Reverse :func:`encode_key`.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
key : str
|
||||
An escaped Realtime Database key.
|
||||
|
||||
Returns:
|
||||
-------
|
||||
str
|
||||
The original segment.
|
||||
|
||||
"""
|
||||
out: list[str] = []
|
||||
index = 0
|
||||
while index < len(key):
|
||||
escape = key[index : index + _ESCAPE_LENGTH]
|
||||
char = _UNESCAPES.get(escape)
|
||||
if char is None:
|
||||
out.append(key[index])
|
||||
index += 1
|
||||
else:
|
||||
out.append(char)
|
||||
index += _ESCAPE_LENGTH
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def encode_path(path: str) -> str:
|
||||
"""Escape every segment of a ``/``-separated logical path.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
path : str
|
||||
A logical path such as ``"todo-sync/notes/abc.json"``.
|
||||
|
||||
Returns:
|
||||
-------
|
||||
str
|
||||
The path with each segment escaped, empty segments dropped.
|
||||
|
||||
"""
|
||||
return "/".join(encode_key(part) for part in path.split("/") if part)
|
||||
|
||||
|
||||
class FirebaseSyncClient:
|
||||
"""Realtime Database seen through the same contract as GitHub.
|
||||
|
||||
|
||||
@ -19,8 +19,15 @@ from typing import TYPE_CHECKING, Protocol
|
||||
|
||||
import requests as _requests
|
||||
|
||||
from crdt_sync._autherrors import FirebaseAuthError, _is_revoked, _reason
|
||||
from crdt_sync._credentials import (
|
||||
CredentialStore,
|
||||
FileCredentialStore,
|
||||
FirebaseCredentials,
|
||||
MemoryCredentialStore,
|
||||
_utcnow,
|
||||
)
|
||||
from crdt_sync._http import new_session
|
||||
from crdt_sync._remote import RemoteSyncError
|
||||
|
||||
# Bound to the name ``requests`` so the call sites below -- and the tests
|
||||
# that patch ``<module>.requests.<verb>`` -- are unchanged by pooling.
|
||||
@ -34,160 +41,6 @@ _SIGN_IN_BASE = "https://identitytoolkit.googleapis.com/v1"
|
||||
_REFRESH_BASE = "https://securetoken.googleapis.com/v1"
|
||||
_DEFAULT_TIMEOUT_SECONDS = 15
|
||||
|
||||
# Refresh this long before the token actually expires. An ID token lives ~1h;
|
||||
# refreshing early means a tick that starts just under the wire still finishes
|
||||
# with a valid token rather than 401ing halfway through a multi-file push.
|
||||
_REFRESH_SKEW = dt.timedelta(minutes=5)
|
||||
|
||||
|
||||
class FirebaseAuthError(RemoteSyncError):
|
||||
"""Raised for an authentication failure the caller must not ignore.
|
||||
|
||||
A :class:`crdt_sync.RemoteSyncError` so callers that only care about
|
||||
"sync is broken" can catch one type, while a settings screen can single
|
||||
this out to say "your password is wrong" rather than "the network is
|
||||
down".
|
||||
"""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FirebaseCredentials:
|
||||
"""One device's session: a short-lived ID token plus its refresh token.
|
||||
|
||||
Attributes:
|
||||
----------
|
||||
id_token:
|
||||
The bearer credential for Realtime Database requests. Expires fast.
|
||||
refresh_token:
|
||||
The long-lived credential. **This is the secret worth protecting.**
|
||||
expires_at:
|
||||
When ``id_token`` stops being accepted, in UTC.
|
||||
"""
|
||||
|
||||
id_token: str
|
||||
refresh_token: str
|
||||
expires_at: dt.datetime
|
||||
|
||||
def is_expired_at(self, now: dt.datetime) -> bool:
|
||||
"""Return whether the token is expired, or close enough to it."""
|
||||
return now + _REFRESH_SKEW >= self.expires_at
|
||||
|
||||
def to_json(self) -> dict[str, str]:
|
||||
"""Return a JSON-serializable form."""
|
||||
return {
|
||||
"id_token": self.id_token,
|
||||
"refresh_token": self.refresh_token,
|
||||
"expires_at": self.expires_at.isoformat(),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, data: dict[str, str]) -> FirebaseCredentials:
|
||||
"""Rebuild credentials from :meth:`to_json` output."""
|
||||
return cls(
|
||||
id_token=data["id_token"],
|
||||
refresh_token=data["refresh_token"],
|
||||
expires_at=dt.datetime.fromisoformat(data["expires_at"]),
|
||||
)
|
||||
|
||||
|
||||
class CredentialStore(Protocol):
|
||||
"""Where a device keeps its credentials between runs."""
|
||||
|
||||
def load(self) -> FirebaseCredentials | None:
|
||||
"""Return the stored credentials, or ``None`` if not signed in."""
|
||||
|
||||
def save(self, credentials: FirebaseCredentials) -> None:
|
||||
"""Persist ``credentials``."""
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Forget any stored credentials."""
|
||||
|
||||
|
||||
class MemoryCredentialStore:
|
||||
"""A :class:`CredentialStore` for tests and one-shot scripts."""
|
||||
|
||||
def __init__(self, credentials: FirebaseCredentials | None = None) -> None:
|
||||
"""Start holding ``credentials`` (or nothing)."""
|
||||
self._credentials = credentials
|
||||
|
||||
def load(self) -> FirebaseCredentials | None:
|
||||
"""Return the held credentials."""
|
||||
return self._credentials
|
||||
|
||||
def save(self, credentials: FirebaseCredentials) -> None:
|
||||
"""Replace the held credentials."""
|
||||
self._credentials = credentials
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Drop the held credentials."""
|
||||
self._credentials = None
|
||||
|
||||
|
||||
class FileCredentialStore:
|
||||
"""A :class:`CredentialStore` backed by a ``0600`` JSON file.
|
||||
|
||||
Persistence is not an optimisation here: ``wake_alarm``'s PC side is a
|
||||
fresh process every minute and ``diet_guard``'s every 15 minutes, so an
|
||||
in-memory store would re-authenticate thousands of times a day.
|
||||
"""
|
||||
|
||||
def __init__(self, path: Path) -> None:
|
||||
"""Store credentials at ``path``, creating parent dirs as needed."""
|
||||
self._path = path
|
||||
|
||||
def load(self) -> FirebaseCredentials | None:
|
||||
"""Return the stored credentials, or ``None`` if the file is absent.
|
||||
|
||||
A corrupt or truncated file (an interrupted write) reads as "not
|
||||
signed in" rather than raising: the caller's next step is to sign in
|
||||
again, which repairs it.
|
||||
"""
|
||||
try:
|
||||
data = json.loads(self._path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
try:
|
||||
return FirebaseCredentials.from_json(data)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None
|
||||
|
||||
def save(self, credentials: FirebaseCredentials) -> None:
|
||||
"""Write ``credentials`` atomically, readable only by this user."""
|
||||
self._path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temp = self._path.with_suffix(f"{self._path.suffix}.tmp")
|
||||
# Create with 0600 from the outset -- writing then chmod'ing would
|
||||
# leave the refresh token world-readable for the gap in between.
|
||||
temp.touch(mode=0o600)
|
||||
temp.write_text(json.dumps(credentials.to_json()), encoding="utf-8")
|
||||
temp.replace(self._path)
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Delete the credentials file if it exists."""
|
||||
self._path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _utcnow() -> dt.datetime:
|
||||
return dt.datetime.now(dt.timezone.utc)
|
||||
|
||||
|
||||
#: Reasons that mean the refresh token is permanently dead. Only these clear
|
||||
#: the session: a network error or a 5xx must not, because a device that signs
|
||||
#: itself out whenever the wifi drops needs a manual sign-in to recover, which
|
||||
#: is a worse failure than the stale banner this guards against.
|
||||
_TERMINAL_AUTH_REASONS = (
|
||||
"TOKEN_EXPIRED",
|
||||
"USER_DISABLED",
|
||||
"USER_NOT_FOUND",
|
||||
"INVALID_REFRESH_TOKEN",
|
||||
"INVALID_GRANT_TYPE",
|
||||
"MISSING_REFRESH_TOKEN",
|
||||
)
|
||||
|
||||
|
||||
def _is_revoked(error: FirebaseAuthError) -> bool:
|
||||
"""Return whether ``error`` means the refresh token is permanently dead."""
|
||||
message = str(error)
|
||||
return any(reason in message for reason in _TERMINAL_AUTH_REASONS)
|
||||
|
||||
|
||||
class FirebaseTokenProvider:
|
||||
@ -387,26 +240,3 @@ class FirebaseTokenProvider:
|
||||
msg = f"failed to {what}: HTTP {response.status_code}{reason}"
|
||||
raise FirebaseAuthError(msg)
|
||||
return response.json()
|
||||
|
||||
|
||||
def _reason(response: _requests.Response) -> str:
|
||||
"""Return Google's machine-readable error reason, in parentheses.
|
||||
|
||||
Pulls ``INVALID_PASSWORD`` / ``TOKEN_EXPIRED`` / ``USER_DISABLED`` out of
|
||||
the body so the raised message says what actually went wrong rather than
|
||||
just reporting a status code.
|
||||
"""
|
||||
try:
|
||||
data = response.json()
|
||||
except ValueError:
|
||||
# A non-JSON body (a proxy error page, say): the status code is all
|
||||
# the detail there is.
|
||||
return ""
|
||||
if not isinstance(data, dict):
|
||||
return ""
|
||||
error = data.get("error")
|
||||
if isinstance(error, dict):
|
||||
return f" ({error.get('message')})"
|
||||
if isinstance(error, str):
|
||||
return f" ({error})"
|
||||
return ""
|
||||
|
||||
30
crdt-sync/crdt_sync/_gherrors.py
Normal file
30
crdt-sync/crdt_sync/_gherrors.py
Normal file
@ -0,0 +1,30 @@
|
||||
"""The errors the GitHub sync backend raises.
|
||||
|
||||
Split from :mod:`crdt_sync._github` for the 250-line cap. Kept separate so a
|
||||
caller can catch them without importing the client -- and so the client file
|
||||
is the client, not its taxonomy.
|
||||
|
||||
Re-exported from :mod:`crdt_sync._github`, so existing imports keep working.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from crdt_sync._remote import RemoteNotFoundError, RemoteSyncError
|
||||
|
||||
|
||||
class GitHubSyncError(RemoteSyncError):
|
||||
"""Raised for a GitHub API failure the caller must not silently ignore."""
|
||||
|
||||
|
||||
class RepoNotFoundError(GitHubSyncError, RemoteNotFoundError):
|
||||
"""Raised when the configured repo itself is unreachable.
|
||||
|
||||
Distinguished from a path-404 (nothing pushed to that path yet, which is
|
||||
benign -- it just means no other device has synced before) so the caller
|
||||
can tell "the repo name is wrong or the token isn't scoped to it" apart
|
||||
from "no other device has synced yet".
|
||||
|
||||
Derives from both so existing ``except GitHubSyncError`` handlers still
|
||||
cover it *and* backend-neutral callers can catch "the remote itself is
|
||||
missing" without naming GitHub.
|
||||
"""
|
||||
@ -13,6 +13,7 @@ import base64
|
||||
|
||||
import requests as _requests
|
||||
|
||||
from crdt_sync._gherrors import GitHubSyncError, RepoNotFoundError
|
||||
from crdt_sync._http import new_session
|
||||
from crdt_sync._remote import RemoteNotFoundError, RemoteSyncError
|
||||
|
||||
@ -26,24 +27,6 @@ _HTTP_NOT_FOUND = 404
|
||||
_DEFAULT_TIMEOUT_SECONDS = 15
|
||||
|
||||
|
||||
class GitHubSyncError(RemoteSyncError):
|
||||
"""Raised for a GitHub API failure the caller must not silently ignore."""
|
||||
|
||||
|
||||
class RepoNotFoundError(GitHubSyncError, RemoteNotFoundError):
|
||||
"""Raised when the configured repo itself is unreachable.
|
||||
|
||||
Distinguished from a path-404 (nothing pushed to that path yet, which is
|
||||
benign -- it just means no other device has synced before) so the caller
|
||||
can tell "the repo name is wrong or the token isn't scoped to it" apart
|
||||
from "no other device has synced yet".
|
||||
|
||||
Derives from both so existing ``except GitHubSyncError`` handlers still
|
||||
cover it *and* backend-neutral callers can catch "the remote itself is
|
||||
missing" without naming GitHub.
|
||||
"""
|
||||
|
||||
|
||||
class GitHubSyncClient:
|
||||
"""Thin wrapper around the subset of the Contents API sync needs."""
|
||||
|
||||
|
||||
109
crdt-sync/crdt_sync/_pull.py
Normal file
109
crdt-sync/crdt_sync/_pull.py
Normal file
@ -0,0 +1,109 @@
|
||||
"""Downloading peers' logs, skipping the ones we already have.
|
||||
|
||||
Split from :mod:`crdt_sync._sync`, which keeps the push half and the
|
||||
orchestration. The revision map is the optimisation that makes a tick cheap:
|
||||
a peer whose published revision matches what we last merged is not fetched at
|
||||
all, so a quiet device costs one small read instead of one read per peer.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
from crdt_sync._log import Log
|
||||
from crdt_sync._remote import RemoteStore
|
||||
|
||||
from crdt_sync._revisions import revision_of
|
||||
from crdt_sync._syncstate import SyncState
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _remote_revs(client: RemoteStore, revs_path: str) -> dict[str, str]:
|
||||
"""Return every peer's published revision, cheaply where possible.
|
||||
|
||||
Degrades to an empty map -- meaning "fetch everything", the old behaviour
|
||||
-- on any backend without a bulk-map read, so correctness never depends
|
||||
on the optimisation being available.
|
||||
"""
|
||||
get_string_map = getattr(client, "get_string_map", None)
|
||||
if get_string_map is None:
|
||||
return {}
|
||||
return get_string_map(revs_path)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _PullContext:
|
||||
"""Everything :func:`_pull_remote_logs` needs for one tick's pull.
|
||||
|
||||
A bundle rather than eight positional parameters: they are always passed
|
||||
together, from one call site, and several share a type -- exactly the
|
||||
shape where a positional mix-up is silent.
|
||||
"""
|
||||
|
||||
client: RemoteStore
|
||||
own_ids: frozenset[str]
|
||||
path_prefix: str
|
||||
filename: str
|
||||
decode: Callable[[str], Log]
|
||||
remote_revs: dict[str, str]
|
||||
state: SyncState
|
||||
|
||||
|
||||
def _pull_remote_logs(
|
||||
ctx: _PullContext,
|
||||
seen_revs: dict[str, str],
|
||||
) -> list[Log]:
|
||||
"""Return every other device's last-pushed log, skipping this one.
|
||||
|
||||
A device whose pushed file is corrupt or unparsable (e.g. an interrupted
|
||||
push) is logged and skipped, same as one that has never pushed at all --
|
||||
the remote is an external system boundary, and one bad device's file must
|
||||
not stall merging in every other device's.
|
||||
|
||||
``own_ids`` is a *set* rather than a single id because a device that has
|
||||
migrated from a role constant to a persisted uuid still owns the log it
|
||||
pushed under the old id. Matching only the current id would pull that
|
||||
file back and re-merge this device's own pre-migration history as though
|
||||
a peer had written it -- idempotent, but pure wasted transfer.
|
||||
|
||||
Records into ``seen_revs`` which peers are now merged in, so the next
|
||||
tick can skip them.
|
||||
"""
|
||||
remote_logs: list[Log] = []
|
||||
for other_device_id in ctx.client.list_directory(ctx.path_prefix):
|
||||
if other_device_id in ctx.own_ids:
|
||||
continue
|
||||
remote_rev = ctx.remote_revs.get(other_device_id)
|
||||
if remote_rev is not None and remote_rev == ctx.state.peer_revs.get(
|
||||
other_device_id
|
||||
):
|
||||
# Unchanged since we last merged it, and that merge is already
|
||||
# part of local_log -- so the (potentially hundreds of KB)
|
||||
# download is pure waste. Carry the revision forward so it stays
|
||||
# skipped next tick.
|
||||
seen_revs[other_device_id] = remote_rev
|
||||
continue
|
||||
text = ctx.client.get_file_text(
|
||||
f"{ctx.path_prefix}/{other_device_id}/{ctx.filename}"
|
||||
)
|
||||
if text is None:
|
||||
continue
|
||||
try:
|
||||
remote_logs.append(ctx.decode(text))
|
||||
except (ValueError, KeyError, TypeError):
|
||||
_logger.warning(
|
||||
"Unparsable log pushed by device %r, skipping",
|
||||
other_device_id,
|
||||
)
|
||||
# Deliberately not recorded as seen: a corrupt push must be
|
||||
# retried next tick, not remembered as merged.
|
||||
continue
|
||||
seen_revs[other_device_id] = remote_rev or revision_of(text)
|
||||
return remote_logs
|
||||
36
crdt-sync/crdt_sync/_revisions.py
Normal file
36
crdt-sync/crdt_sync/_revisions.py
Normal file
@ -0,0 +1,36 @@
|
||||
"""The revision string a device publishes alongside its log.
|
||||
|
||||
Split from :mod:`crdt_sync._sync` so both the push and pull halves can import
|
||||
it without importing each other. Pure: a revision is a function of the encoded
|
||||
log and nothing else, which is what lets two devices agree on whether they are
|
||||
looking at the same bytes.
|
||||
|
||||
Re-exported from :mod:`crdt_sync._sync`, so existing imports keep working.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
|
||||
def revision_of(encoded_log: str) -> str:
|
||||
"""Return the revision of a serialized log: a content hash.
|
||||
|
||||
A hash rather than the log's maximum HLC because merging a peer's *older*
|
||||
record changes the content without raising the maximum -- with three
|
||||
devices in one namespace (diet-guard has ``pc``, ``phone`` and
|
||||
``desktop``) a clock-based revision can miss a peer's merged state. It is
|
||||
also the same value used to suppress no-op pushes, so the two
|
||||
optimisations share one mechanism.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
encoded_log : str
|
||||
The serialized log, exactly as it would be pushed.
|
||||
|
||||
Returns:
|
||||
-------
|
||||
str
|
||||
A hex SHA-256 digest.
|
||||
|
||||
"""
|
||||
return hashlib.sha256(encoded_log.encode("utf-8")).hexdigest()
|
||||
@ -26,147 +26,20 @@ if TYPE_CHECKING:
|
||||
from crdt_sync._log import Log
|
||||
from crdt_sync._remote import RemoteStore
|
||||
|
||||
from crdt_sync._pull import _PullContext, _pull_remote_logs, _remote_revs
|
||||
from crdt_sync._revisions import revision_of
|
||||
from crdt_sync._syncstate import (
|
||||
FileSyncStateStore,
|
||||
MemorySyncStateStore,
|
||||
SyncState,
|
||||
SyncStateStore,
|
||||
)
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_DEFAULT_FILENAME = "log.json"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SyncState:
|
||||
"""What one device remembers between ticks to skip needless traffic.
|
||||
|
||||
Attributes:
|
||||
----------
|
||||
pushed_rev:
|
||||
Hash of what this device last pushed, so an unchanged log is not
|
||||
re-uploaded. 88% of the pushes in the GitHub-backed history this
|
||||
replaces were byte-identical no-ops.
|
||||
peer_revs:
|
||||
The hash each peer had when we last downloaded it, so an unchanged
|
||||
peer is not re-downloaded.
|
||||
|
||||
Notes:
|
||||
-----
|
||||
**Must be stored next to the log itself and cleared with it.** Skipping
|
||||
an unchanged peer is only sound because that peer's records are already
|
||||
merged into the local log; a cache that outlived its log would skip peers
|
||||
whose data had been lost.
|
||||
|
||||
"""
|
||||
|
||||
pushed_rev: str | None = None
|
||||
peer_revs: dict[str, str] = field(default_factory=dict)
|
||||
|
||||
def to_json(self) -> dict[str, object]:
|
||||
"""Return a JSON-serializable form."""
|
||||
return {"pushed_rev": self.pushed_rev, "peer_revs": self.peer_revs}
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, data: dict[str, object]) -> SyncState:
|
||||
"""Rebuild state from :meth:`to_json` output, ignoring junk.
|
||||
|
||||
A malformed cache degrades into "fetch everything" rather than
|
||||
raising: it is an optimisation, never a source of failure.
|
||||
"""
|
||||
pushed = data.get("pushed_rev")
|
||||
peers = data.get("peer_revs")
|
||||
return cls(
|
||||
pushed_rev=pushed if isinstance(pushed, str) else None,
|
||||
peer_revs={
|
||||
key: value
|
||||
for key, value in (peers or {}).items()
|
||||
if isinstance(value, str)
|
||||
}
|
||||
if isinstance(peers, dict)
|
||||
else {},
|
||||
)
|
||||
|
||||
|
||||
class SyncStateStore(Protocol):
|
||||
"""Where :func:`sync_log` persists its :class:`SyncState` between runs."""
|
||||
|
||||
def load(self) -> SyncState:
|
||||
"""Return the stored state, or a default one."""
|
||||
|
||||
def save(self, state: SyncState) -> None:
|
||||
"""Persist ``state``."""
|
||||
|
||||
|
||||
class MemorySyncStateStore:
|
||||
"""A :class:`SyncStateStore` that forgets on exit, for tests.
|
||||
|
||||
Correct but pessimistic: every process re-downloads every peer and
|
||||
re-pushes the local log, which is exactly the old behaviour.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Start with empty state."""
|
||||
self._state = SyncState()
|
||||
|
||||
def load(self) -> SyncState:
|
||||
"""Return the held state."""
|
||||
return self._state
|
||||
|
||||
def save(self, state: SyncState) -> None:
|
||||
"""Replace the held state."""
|
||||
self._state = state
|
||||
|
||||
|
||||
class FileSyncStateStore:
|
||||
"""A :class:`SyncStateStore` backed by a JSON file.
|
||||
|
||||
Persistence is what makes the saving real for short-lived callers:
|
||||
``wake_alarm``'s PC side is a fresh process every minute and
|
||||
``diet_guard``'s every 15 minutes, so an in-memory store would save
|
||||
nothing at all.
|
||||
"""
|
||||
|
||||
def __init__(self, path: Path) -> None:
|
||||
"""Keep state in the file at ``path``."""
|
||||
self._path = path
|
||||
|
||||
def load(self) -> SyncState:
|
||||
"""Return the stored state, or a default one if unreadable."""
|
||||
try:
|
||||
data = json.loads(self._path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return SyncState()
|
||||
if not isinstance(data, dict):
|
||||
return SyncState()
|
||||
return SyncState.from_json(data)
|
||||
|
||||
def save(self, state: SyncState) -> None:
|
||||
"""Write ``state`` atomically, so a crash cannot truncate it."""
|
||||
self._path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temp = self._path.with_suffix(f"{self._path.suffix}.tmp")
|
||||
temp.write_text(json.dumps(state.to_json()), encoding="utf-8")
|
||||
temp.replace(self._path)
|
||||
|
||||
|
||||
def revision_of(encoded_log: str) -> str:
|
||||
"""Return the revision of a serialized log: a content hash.
|
||||
|
||||
A hash rather than the log's maximum HLC because merging a peer's *older*
|
||||
record changes the content without raising the maximum -- with three
|
||||
devices in one namespace (diet-guard has ``pc``, ``phone`` and
|
||||
``desktop``) a clock-based revision can miss a peer's merged state. It is
|
||||
also the same value used to suppress no-op pushes, so the two
|
||||
optimisations share one mechanism.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
encoded_log : str
|
||||
The serialized log, exactly as it would be pushed.
|
||||
|
||||
Returns:
|
||||
-------
|
||||
str
|
||||
A hex SHA-256 digest.
|
||||
|
||||
"""
|
||||
return hashlib.sha256(encoded_log.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def default_revs_path(path_prefix: str) -> str:
|
||||
"""Return where revisions live for ``path_prefix``.
|
||||
|
||||
@ -189,90 +62,6 @@ def default_revs_path(path_prefix: str) -> str:
|
||||
return f"{head}/revs" if separator else f"{path_prefix}/revs"
|
||||
|
||||
|
||||
def _remote_revs(client: RemoteStore, revs_path: str) -> dict[str, str]:
|
||||
"""Return every peer's published revision, cheaply where possible.
|
||||
|
||||
Degrades to an empty map -- meaning "fetch everything", the old behaviour
|
||||
-- on any backend without a bulk-map read, so correctness never depends
|
||||
on the optimisation being available.
|
||||
"""
|
||||
get_string_map = getattr(client, "get_string_map", None)
|
||||
if get_string_map is None:
|
||||
return {}
|
||||
return get_string_map(revs_path)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _PullContext:
|
||||
"""Everything :func:`_pull_remote_logs` needs for one tick's pull.
|
||||
|
||||
A bundle rather than eight positional parameters: they are always passed
|
||||
together, from one call site, and several share a type -- exactly the
|
||||
shape where a positional mix-up is silent.
|
||||
"""
|
||||
|
||||
client: RemoteStore
|
||||
own_ids: frozenset[str]
|
||||
path_prefix: str
|
||||
filename: str
|
||||
decode: Callable[[str], Log]
|
||||
remote_revs: dict[str, str]
|
||||
state: SyncState
|
||||
|
||||
|
||||
def _pull_remote_logs(
|
||||
ctx: _PullContext,
|
||||
seen_revs: dict[str, str],
|
||||
) -> list[Log]:
|
||||
"""Return every other device's last-pushed log, skipping this one.
|
||||
|
||||
A device whose pushed file is corrupt or unparsable (e.g. an interrupted
|
||||
push) is logged and skipped, same as one that has never pushed at all --
|
||||
the remote is an external system boundary, and one bad device's file must
|
||||
not stall merging in every other device's.
|
||||
|
||||
``own_ids`` is a *set* rather than a single id because a device that has
|
||||
migrated from a role constant to a persisted uuid still owns the log it
|
||||
pushed under the old id. Matching only the current id would pull that
|
||||
file back and re-merge this device's own pre-migration history as though
|
||||
a peer had written it -- idempotent, but pure wasted transfer.
|
||||
|
||||
Records into ``seen_revs`` which peers are now merged in, so the next
|
||||
tick can skip them.
|
||||
"""
|
||||
remote_logs: list[Log] = []
|
||||
for other_device_id in ctx.client.list_directory(ctx.path_prefix):
|
||||
if other_device_id in ctx.own_ids:
|
||||
continue
|
||||
remote_rev = ctx.remote_revs.get(other_device_id)
|
||||
if remote_rev is not None and remote_rev == ctx.state.peer_revs.get(
|
||||
other_device_id
|
||||
):
|
||||
# Unchanged since we last merged it, and that merge is already
|
||||
# part of local_log -- so the (potentially hundreds of KB)
|
||||
# download is pure waste. Carry the revision forward so it stays
|
||||
# skipped next tick.
|
||||
seen_revs[other_device_id] = remote_rev
|
||||
continue
|
||||
text = ctx.client.get_file_text(
|
||||
f"{ctx.path_prefix}/{other_device_id}/{ctx.filename}"
|
||||
)
|
||||
if text is None:
|
||||
continue
|
||||
try:
|
||||
remote_logs.append(ctx.decode(text))
|
||||
except (ValueError, KeyError, TypeError):
|
||||
_logger.warning(
|
||||
"Unparsable log pushed by device %r, skipping",
|
||||
other_device_id,
|
||||
)
|
||||
# Deliberately not recorded as seen: a corrupt push must be
|
||||
# retried next tick, not remembered as merged.
|
||||
continue
|
||||
seen_revs[other_device_id] = remote_rev or revision_of(text)
|
||||
return remote_logs
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SyncTarget:
|
||||
"""Which remote, which device, and where its logs live.
|
||||
|
||||
131
crdt-sync/crdt_sync/_syncstate.py
Normal file
131
crdt-sync/crdt_sync/_syncstate.py
Normal file
@ -0,0 +1,131 @@
|
||||
"""Where a device records what it has already pushed and pulled.
|
||||
|
||||
Split from :mod:`crdt_sync._sync`, which keeps the sync itself. The state is
|
||||
what makes a tick cheap: without it every run re-downloads every peer, and
|
||||
with a stale one a device silently stops seeing updates. Two stores ship --
|
||||
in-memory for tests, and a JSON file for real installs.
|
||||
|
||||
Re-exported from :mod:`crdt_sync._sync`, so existing imports keep working.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Protocol
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SyncState:
|
||||
"""What one device remembers between ticks to skip needless traffic.
|
||||
|
||||
Attributes:
|
||||
----------
|
||||
pushed_rev:
|
||||
Hash of what this device last pushed, so an unchanged log is not
|
||||
re-uploaded. 88% of the pushes in the GitHub-backed history this
|
||||
replaces were byte-identical no-ops.
|
||||
peer_revs:
|
||||
The hash each peer had when we last downloaded it, so an unchanged
|
||||
peer is not re-downloaded.
|
||||
|
||||
Notes:
|
||||
-----
|
||||
**Must be stored next to the log itself and cleared with it.** Skipping
|
||||
an unchanged peer is only sound because that peer's records are already
|
||||
merged into the local log; a cache that outlived its log would skip peers
|
||||
whose data had been lost.
|
||||
|
||||
"""
|
||||
|
||||
pushed_rev: str | None = None
|
||||
peer_revs: dict[str, str] = field(default_factory=dict)
|
||||
|
||||
def to_json(self) -> dict[str, object]:
|
||||
"""Return a JSON-serializable form."""
|
||||
return {"pushed_rev": self.pushed_rev, "peer_revs": self.peer_revs}
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, data: dict[str, object]) -> SyncState:
|
||||
"""Rebuild state from :meth:`to_json` output, ignoring junk.
|
||||
|
||||
A malformed cache degrades into "fetch everything" rather than
|
||||
raising: it is an optimisation, never a source of failure.
|
||||
"""
|
||||
pushed = data.get("pushed_rev")
|
||||
peers = data.get("peer_revs")
|
||||
return cls(
|
||||
pushed_rev=pushed if isinstance(pushed, str) else None,
|
||||
peer_revs={
|
||||
key: value
|
||||
for key, value in (peers or {}).items()
|
||||
if isinstance(value, str)
|
||||
}
|
||||
if isinstance(peers, dict)
|
||||
else {},
|
||||
)
|
||||
|
||||
|
||||
class SyncStateStore(Protocol):
|
||||
"""Where :func:`sync_log` persists its :class:`SyncState` between runs."""
|
||||
|
||||
def load(self) -> SyncState:
|
||||
"""Return the stored state, or a default one."""
|
||||
|
||||
def save(self, state: SyncState) -> None:
|
||||
"""Persist ``state``."""
|
||||
|
||||
|
||||
class MemorySyncStateStore:
|
||||
"""A :class:`SyncStateStore` that forgets on exit, for tests.
|
||||
|
||||
Correct but pessimistic: every process re-downloads every peer and
|
||||
re-pushes the local log, which is exactly the old behaviour.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Start with empty state."""
|
||||
self._state = SyncState()
|
||||
|
||||
def load(self) -> SyncState:
|
||||
"""Return the held state."""
|
||||
return self._state
|
||||
|
||||
def save(self, state: SyncState) -> None:
|
||||
"""Replace the held state."""
|
||||
self._state = state
|
||||
|
||||
|
||||
class FileSyncStateStore:
|
||||
"""A :class:`SyncStateStore` backed by a JSON file.
|
||||
|
||||
Persistence is what makes the saving real for short-lived callers:
|
||||
``wake_alarm``'s PC side is a fresh process every minute and
|
||||
``diet_guard``'s every 15 minutes, so an in-memory store would save
|
||||
nothing at all.
|
||||
"""
|
||||
|
||||
def __init__(self, path: Path) -> None:
|
||||
"""Keep state in the file at ``path``."""
|
||||
self._path = path
|
||||
|
||||
def load(self) -> SyncState:
|
||||
"""Return the stored state, or a default one if unreadable."""
|
||||
try:
|
||||
data = json.loads(self._path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return SyncState()
|
||||
if not isinstance(data, dict):
|
||||
return SyncState()
|
||||
return SyncState.from_json(data)
|
||||
|
||||
def save(self, state: SyncState) -> None:
|
||||
"""Write ``state`` atomically, so a crash cannot truncate it."""
|
||||
self._path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temp = self._path.with_suffix(f"{self._path.suffix}.tmp")
|
||||
temp.write_text(json.dumps(state.to_json()), encoding="utf-8")
|
||||
temp.replace(self._path)
|
||||
109
crdt-sync/tool/_oauth_callback.py
Normal file
109
crdt-sync/tool/_oauth_callback.py
Normal file
@ -0,0 +1,109 @@
|
||||
"""The one-shot local HTTP server that catches Google's OAuth redirect.
|
||||
|
||||
Split from :mod:`google_id_token`, which keeps the token exchange. Google
|
||||
redirects the browser back to ``http://localhost:<port>`` with the code in the
|
||||
query string, so something has to be listening on a free port for exactly one
|
||||
request and then stop.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import http.server
|
||||
import time
|
||||
import urllib.parse
|
||||
import logging
|
||||
import socket
|
||||
import threading
|
||||
from typing import TYPE_CHECKING, ClassVar
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_CONSENT_TIMEOUT_SECONDS = 300
|
||||
|
||||
|
||||
class _CallbackHandler(http.server.BaseHTTPRequestHandler):
|
||||
"""Captures the ``code`` (or ``error``) Google redirects back with."""
|
||||
|
||||
# Set by the server owner before serving. Class attributes because
|
||||
# BaseHTTPRequestHandler is instantiated per request by the server, so
|
||||
# there is no instance to hand them to.
|
||||
expected_state: ClassVar[str] = ""
|
||||
result: ClassVar[dict[str, str]] = {}
|
||||
|
||||
def do_GET(self) -> None:
|
||||
"""Record the query parameters and show a closable page.
|
||||
|
||||
Requests that carry neither a ``code`` nor an ``error`` are answered
|
||||
but *not* recorded: browsers fetch ``/favicon.ico`` against the
|
||||
redirect origin, and letting that count as the callback ends the flow
|
||||
before Google ever redirects, which surfaces as a consent timeout.
|
||||
"""
|
||||
query = urllib.parse.urlparse(self.path).query
|
||||
params = {k: v[0] for k, v in urllib.parse.parse_qs(query).items()}
|
||||
if "code" not in params and "error" not in params:
|
||||
self.send_response(204)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
return
|
||||
type(self).result = params
|
||||
|
||||
ok = "code" in params and params.get("state") == self.expected_state
|
||||
body = (
|
||||
b"<html><body><h2>Done - you can close this tab.</h2></body></html>"
|
||||
if ok
|
||||
else b"<html><body><h2>Authorization failed.</h2></body></html>"
|
||||
)
|
||||
self.send_response(200 if ok else 400)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args: object) -> None:
|
||||
"""Silence the default stderr request logging."""
|
||||
|
||||
|
||||
def _free_port() -> int:
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
return int(sock.getsockname()[1])
|
||||
|
||||
|
||||
def _start_callback_server(
|
||||
port: int,
|
||||
state: str,
|
||||
) -> tuple[http.server.HTTPServer, threading.Thread]:
|
||||
"""Listen on ``port`` until the OAuth callback arrives.
|
||||
|
||||
Serves in a loop rather than handling exactly one request: the first
|
||||
request to reach this port is often a favicon fetch or a speculative
|
||||
preconnect, and retiring the server on it leaves nothing listening when
|
||||
Google finally redirects -- which surfaces as a consent timeout.
|
||||
|
||||
Args:
|
||||
port: The loopback port to bind.
|
||||
state: The value the callback must echo back.
|
||||
|
||||
Returns:
|
||||
The server and the thread serving it, so the caller can join and close.
|
||||
"""
|
||||
_CallbackHandler.expected_state = state
|
||||
_CallbackHandler.result = {}
|
||||
server = http.server.HTTPServer(("127.0.0.1", port), _CallbackHandler)
|
||||
# Bounded so handle_request() returns periodically instead of blocking
|
||||
# forever; without it the loop could not notice the deadline and the
|
||||
# daemon thread would sit on the socket after the caller gave up.
|
||||
server.timeout = 1.0
|
||||
deadline = time.monotonic() + _CONSENT_TIMEOUT_SECONDS
|
||||
|
||||
def _serve_until_callback() -> None:
|
||||
while not _CallbackHandler.result and time.monotonic() < deadline:
|
||||
server.handle_request()
|
||||
|
||||
thread = threading.Thread(target=_serve_until_callback, daemon=True)
|
||||
thread.start()
|
||||
return server, thread
|
||||
@ -62,99 +62,22 @@ _TOKEN_EXCHANGE_URL = f"{_OAUTH_HOST}/token"
|
||||
_SCOPES = "openid email profile"
|
||||
|
||||
_TIMEOUT_SECONDS = 30
|
||||
_CONSENT_TIMEOUT_SECONDS = 300
|
||||
|
||||
_logger = logging.getLogger("google_id_token")
|
||||
|
||||
|
||||
from tool._oauth_callback import (
|
||||
_CONSENT_TIMEOUT_SECONDS,
|
||||
_CallbackHandler,
|
||||
_free_port,
|
||||
_start_callback_server,
|
||||
)
|
||||
|
||||
|
||||
class TokenError(Exception):
|
||||
"""The authorization flow did not produce an ID token."""
|
||||
|
||||
|
||||
class _CallbackHandler(http.server.BaseHTTPRequestHandler):
|
||||
"""Captures the ``code`` (or ``error``) Google redirects back with."""
|
||||
|
||||
# Set by the server owner before serving. Class attributes because
|
||||
# BaseHTTPRequestHandler is instantiated per request by the server, so
|
||||
# there is no instance to hand them to.
|
||||
expected_state: ClassVar[str] = ""
|
||||
result: ClassVar[dict[str, str]] = {}
|
||||
|
||||
def do_GET(self) -> None:
|
||||
"""Record the query parameters and show a closable page.
|
||||
|
||||
Requests that carry neither a ``code`` nor an ``error`` are answered
|
||||
but *not* recorded: browsers fetch ``/favicon.ico`` against the
|
||||
redirect origin, and letting that count as the callback ends the flow
|
||||
before Google ever redirects, which surfaces as a consent timeout.
|
||||
"""
|
||||
query = urllib.parse.urlparse(self.path).query
|
||||
params = {k: v[0] for k, v in urllib.parse.parse_qs(query).items()}
|
||||
if "code" not in params and "error" not in params:
|
||||
self.send_response(204)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
return
|
||||
type(self).result = params
|
||||
|
||||
ok = "code" in params and params.get("state") == self.expected_state
|
||||
body = (
|
||||
b"<html><body><h2>Done - you can close this tab.</h2></body></html>"
|
||||
if ok
|
||||
else b"<html><body><h2>Authorization failed.</h2></body></html>"
|
||||
)
|
||||
self.send_response(200 if ok else 400)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args: object) -> None:
|
||||
"""Silence the default stderr request logging."""
|
||||
|
||||
|
||||
def _free_port() -> int:
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
return int(sock.getsockname()[1])
|
||||
|
||||
|
||||
def _start_callback_server(
|
||||
port: int,
|
||||
state: str,
|
||||
) -> tuple[http.server.HTTPServer, threading.Thread]:
|
||||
"""Listen on ``port`` until the OAuth callback arrives.
|
||||
|
||||
Serves in a loop rather than handling exactly one request: the first
|
||||
request to reach this port is often a favicon fetch or a speculative
|
||||
preconnect, and retiring the server on it leaves nothing listening when
|
||||
Google finally redirects -- which surfaces as a consent timeout.
|
||||
|
||||
Args:
|
||||
port: The loopback port to bind.
|
||||
state: The value the callback must echo back.
|
||||
|
||||
Returns:
|
||||
The server and the thread serving it, so the caller can join and close.
|
||||
"""
|
||||
_CallbackHandler.expected_state = state
|
||||
_CallbackHandler.result = {}
|
||||
server = http.server.HTTPServer(("127.0.0.1", port), _CallbackHandler)
|
||||
# Bounded so handle_request() returns periodically instead of blocking
|
||||
# forever; without it the loop could not notice the deadline and the
|
||||
# daemon thread would sit on the socket after the caller gave up.
|
||||
server.timeout = 1.0
|
||||
deadline = time.monotonic() + _CONSENT_TIMEOUT_SECONDS
|
||||
|
||||
def _serve_until_callback() -> None:
|
||||
while not _CallbackHandler.result and time.monotonic() < deadline:
|
||||
server.handle_request()
|
||||
|
||||
thread = threading.Thread(target=_serve_until_callback, daemon=True)
|
||||
thread.start()
|
||||
return server, thread
|
||||
|
||||
|
||||
def fetch_id_token(
|
||||
client_id: str,
|
||||
client_secret: str,
|
||||
|
||||
@ -32,10 +32,10 @@ from gatelock._outputs import (
|
||||
OutputEnumerator,
|
||||
OutputRect,
|
||||
OutputScan,
|
||||
RandrBackend,
|
||||
enumerate_outputs,
|
||||
parse_xrandr_query,
|
||||
)
|
||||
from gatelock._randr import RandrBackend
|
||||
from gatelock._xrandr import parse_xrandr_query
|
||||
from gatelock._queue import (
|
||||
QUEUE_DEADLINE_SECONDS,
|
||||
QUEUE_POLL_SECONDS,
|
||||
|
||||
@ -30,33 +30,48 @@ arms anyway. See :meth:`Arbiter.evaluate`.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
import errno
|
||||
import fcntl
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
from typing import IO, Final, Literal
|
||||
from typing import IO, Final
|
||||
import uuid
|
||||
|
||||
from gatelock._claims import (
|
||||
ArbiterVerdict,
|
||||
Claim,
|
||||
_try_lock,
|
||||
default_runtime_dir,
|
||||
grab_strength,
|
||||
live_claims,
|
||||
read_claim_if_held,
|
||||
)
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# Re-exported after the 250-line split: `from gatelock._arbiter import
|
||||
# Claim` is used by _window, the tests and gatelock's own __init__.
|
||||
__all__ = [
|
||||
"RANK_DIET_GUARD",
|
||||
"RANK_SCREEN_LOCKER",
|
||||
"RANK_WAKE_ALARM",
|
||||
"Arbiter",
|
||||
"ArbiterVerdict",
|
||||
"Claim",
|
||||
"default_runtime_dir",
|
||||
"grab_strength",
|
||||
]
|
||||
|
||||
|
||||
RANK_WAKE_ALARM: Final = 300
|
||||
RANK_SCREEN_LOCKER: Final = 200
|
||||
RANK_DIET_GUARD: Final = 100
|
||||
|
||||
_RUNTIME_DIR_ENV: Final = "GATELOCK_RUNTIME_DIR"
|
||||
_CLAIMS_DIRNAME: Final = "claims"
|
||||
_HOLDER_FILENAME: Final = "holder.lock"
|
||||
|
||||
# Ordering for the strength check. A stand-down is only safe towards an
|
||||
# incumbent whose grab is at least this strong.
|
||||
_GRAB_STRENGTH: Final[dict[str, int]] = {"none": 0, "local": 1, "global": 2}
|
||||
|
||||
VerdictReason = Literal["clear", "outranked", "weaker-incumbent-armed-anyway"]
|
||||
|
||||
|
||||
def _utc_now_iso() -> str:
|
||||
@ -64,133 +79,6 @@ def _utc_now_iso() -> str:
|
||||
return datetime.now(tz=timezone.utc).isoformat()
|
||||
|
||||
|
||||
def grab_strength(grab: str) -> int:
|
||||
"""Return the comparable strength of a grab kind.
|
||||
|
||||
Unknown values sort as the weakest possible, so a future grab kind can
|
||||
never be silently treated as strong enough to stand down for.
|
||||
"""
|
||||
return _GRAB_STRENGTH.get(grab, 0)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Claim:
|
||||
"""One app's declared intent to hold the screen."""
|
||||
|
||||
app: str
|
||||
rank: int
|
||||
pid: int
|
||||
started: str
|
||||
grab: str
|
||||
disable_vt: bool
|
||||
instance_id: str
|
||||
"""Identifies the *arbiter*, not the process.
|
||||
|
||||
A pid is not unique enough: one process may legitimately host two
|
||||
arbiters, and the whole test suite does exactly that to exercise real
|
||||
``flock`` contention without spawning subprocesses.
|
||||
"""
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Serialise this claim for its on-disk file."""
|
||||
return json.dumps(
|
||||
{
|
||||
"app": self.app,
|
||||
"rank": self.rank,
|
||||
"pid": self.pid,
|
||||
"started": self.started,
|
||||
"grab": self.grab,
|
||||
"disable_vt": self.disable_vt,
|
||||
"instance_id": self.instance_id,
|
||||
}
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, text: str) -> Claim | None:
|
||||
"""Parse a claim file's contents, or None if it is unusable.
|
||||
|
||||
A malformed claim is treated as absent rather than fatal: a half-written
|
||||
file must never be able to stop a locker from arming.
|
||||
"""
|
||||
try:
|
||||
raw = json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
try:
|
||||
return cls(
|
||||
app=str(raw["app"]),
|
||||
rank=int(raw["rank"]),
|
||||
pid=int(raw["pid"]),
|
||||
started=str(raw["started"]),
|
||||
grab=str(raw["grab"]),
|
||||
disable_vt=bool(raw["disable_vt"]),
|
||||
instance_id=str(raw["instance_id"]),
|
||||
)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None
|
||||
|
||||
def at_least_as_strong_as(self, other: Claim) -> bool:
|
||||
"""Whether this claim locks at least as firmly as ``other``."""
|
||||
return (
|
||||
grab_strength(self.grab) >= grab_strength(other.grab)
|
||||
and self.disable_vt >= other.disable_vt
|
||||
)
|
||||
|
||||
def sort_key(self) -> tuple[int, str, int]:
|
||||
"""Rank descending, then earliest start, then lowest pid."""
|
||||
return (-self.rank, self.started, self.pid)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ArbiterVerdict:
|
||||
"""Whether this app may arm, and why."""
|
||||
|
||||
may_arm: bool
|
||||
blocked_by: Claim | None
|
||||
reason: VerdictReason
|
||||
|
||||
|
||||
def default_runtime_dir() -> Path:
|
||||
"""Return the directory holding claims and the holder lock.
|
||||
|
||||
Prefers ``$XDG_RUNTIME_DIR`` (tmpfs, so it self-clears on reboot) and falls
|
||||
back to a per-uid temp directory when that is unset or unwritable.
|
||||
"""
|
||||
override = os.environ.get(_RUNTIME_DIR_ENV)
|
||||
if override:
|
||||
return Path(override)
|
||||
xdg = os.environ.get("XDG_RUNTIME_DIR")
|
||||
if xdg:
|
||||
return Path(xdg) / "gatelock"
|
||||
return Path(tempfile.gettempdir()) / f"gatelock-{os.getuid()}"
|
||||
|
||||
|
||||
def _try_lock(handle: IO[str]) -> bool:
|
||||
"""Try to take an exclusive non-blocking flock. True if acquired."""
|
||||
try:
|
||||
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except OSError as exc:
|
||||
if exc.errno in {errno.EACCES, errno.EAGAIN}:
|
||||
return False
|
||||
raise
|
||||
return True
|
||||
|
||||
|
||||
def _same_file(handle: IO[str], path: Path) -> bool:
|
||||
"""Whether ``path`` still names the file behind ``handle``.
|
||||
|
||||
Guards the reap below: between locking a dead app's claim and unlinking it,
|
||||
a fresh process may have recreated the same path. Comparing inodes stops us
|
||||
deleting the newcomer's claim.
|
||||
"""
|
||||
try:
|
||||
return os.fstat(handle.fileno()).st_ino == path.stat().st_ino
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
class Arbiter:
|
||||
"""Publishes this app's claim and reports whether it may arm."""
|
||||
|
||||
@ -262,42 +150,10 @@ class Arbiter:
|
||||
"""Return every claim whose owning process is still alive.
|
||||
|
||||
Dead owners' claims are reaped as a side effect -- proving a claim is
|
||||
stale and deleting it are the same operation.
|
||||
stale and deleting it are the same operation. See
|
||||
:func:`gatelock._claims.live_claims`.
|
||||
"""
|
||||
if not self._claims_dir.is_dir():
|
||||
return ()
|
||||
claims: list[Claim] = []
|
||||
for path in sorted(self._claims_dir.glob("*.json")):
|
||||
claim = self._read_if_live(path)
|
||||
if claim is not None:
|
||||
claims.append(claim)
|
||||
return tuple(sorted(claims, key=Claim.sort_key))
|
||||
|
||||
def _read_if_live(self, path: Path) -> Claim | None:
|
||||
"""Return the claim at ``path`` if its owner is alive; else reap it."""
|
||||
try:
|
||||
handle = path.open("r+", encoding="utf-8")
|
||||
except OSError:
|
||||
return None
|
||||
with handle:
|
||||
if _try_lock(handle):
|
||||
# We got the lock, so nobody holds it, so the owner is gone.
|
||||
self._reap(handle, path)
|
||||
return None
|
||||
try:
|
||||
return Claim.from_json(handle.read())
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
def _reap(self, handle: IO[str], path: Path) -> None:
|
||||
"""Delete a claim whose owner has died, unless it was recreated."""
|
||||
if not _same_file(handle, path):
|
||||
_logger.debug("claim %s was recreated while reaping; leaving it", path)
|
||||
return
|
||||
try:
|
||||
path.unlink()
|
||||
except OSError as exc:
|
||||
_logger.debug("could not reap stale claim %s: %s", path, exc)
|
||||
return live_claims(self._claims_dir)
|
||||
|
||||
def evaluate(self) -> ArbiterVerdict:
|
||||
"""Decide whether this app may arm.
|
||||
@ -365,14 +221,7 @@ class Arbiter:
|
||||
return None
|
||||
if self._holder_handle is not None:
|
||||
return self._claim
|
||||
try:
|
||||
with path.open("r+", encoding="utf-8") as handle:
|
||||
if _try_lock(handle):
|
||||
# Lock was free, so no live app holds the screen.
|
||||
return None
|
||||
return Claim.from_json(handle.read())
|
||||
except OSError:
|
||||
return None
|
||||
return read_claim_if_held(path)
|
||||
|
||||
def release(self) -> None:
|
||||
"""Drop the holder lock and this app's claim.
|
||||
|
||||
237
gatelock/gatelock/_claims.py
Normal file
237
gatelock/gatelock/_claims.py
Normal file
@ -0,0 +1,237 @@
|
||||
"""The claim an app publishes while it holds the screen, and how to read one.
|
||||
|
||||
Split from :mod:`gatelock._arbiter`, which keeps the arbiter itself. A claim
|
||||
is a small JSON document under the runtime dir, held open with an advisory
|
||||
lock for as long as its process lives -- so "is this claim live?" is answered
|
||||
by trying to take that lock, not by trusting the file's contents.
|
||||
|
||||
Re-exported from :mod:`gatelock._arbiter`, so existing imports keep working.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import errno
|
||||
import fcntl
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
from typing import IO, Final, Literal
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_RUNTIME_DIR_ENV: Final = "GATELOCK_RUNTIME_DIR"
|
||||
|
||||
VerdictReason = Literal["clear", "outranked", "weaker-incumbent-armed-anyway"]
|
||||
|
||||
|
||||
_GRAB_STRENGTH: Final[dict[str, int]] = {"none": 0, "local": 1, "global": 2}
|
||||
|
||||
|
||||
def grab_strength(grab: str) -> int:
|
||||
"""Return the comparable strength of a grab kind.
|
||||
|
||||
Unknown values sort as the weakest possible, so a future grab kind can
|
||||
never be silently treated as strong enough to stand down for.
|
||||
"""
|
||||
return _GRAB_STRENGTH.get(grab, 0)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Claim:
|
||||
"""One app's declared intent to hold the screen."""
|
||||
|
||||
app: str
|
||||
rank: int
|
||||
pid: int
|
||||
started: str
|
||||
grab: str
|
||||
disable_vt: bool
|
||||
instance_id: str
|
||||
"""Identifies the *arbiter*, not the process.
|
||||
|
||||
A pid is not unique enough: one process may legitimately host two
|
||||
arbiters, and the whole test suite does exactly that to exercise real
|
||||
``flock`` contention without spawning subprocesses.
|
||||
"""
|
||||
|
||||
def to_json(self) -> str:
|
||||
"""Serialise this claim for its on-disk file."""
|
||||
return json.dumps(
|
||||
{
|
||||
"app": self.app,
|
||||
"rank": self.rank,
|
||||
"pid": self.pid,
|
||||
"started": self.started,
|
||||
"grab": self.grab,
|
||||
"disable_vt": self.disable_vt,
|
||||
"instance_id": self.instance_id,
|
||||
}
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, text: str) -> Claim | None:
|
||||
"""Parse a claim file's contents, or None if it is unusable.
|
||||
|
||||
A malformed claim is treated as absent rather than fatal: a half-written
|
||||
file must never be able to stop a locker from arming.
|
||||
"""
|
||||
try:
|
||||
raw = json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
try:
|
||||
return cls(
|
||||
app=str(raw["app"]),
|
||||
rank=int(raw["rank"]),
|
||||
pid=int(raw["pid"]),
|
||||
started=str(raw["started"]),
|
||||
grab=str(raw["grab"]),
|
||||
disable_vt=bool(raw["disable_vt"]),
|
||||
instance_id=str(raw["instance_id"]),
|
||||
)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None
|
||||
|
||||
def at_least_as_strong_as(self, other: Claim) -> bool:
|
||||
"""Whether this claim locks at least as firmly as ``other``."""
|
||||
return (
|
||||
grab_strength(self.grab) >= grab_strength(other.grab)
|
||||
and self.disable_vt >= other.disable_vt
|
||||
)
|
||||
|
||||
def sort_key(self) -> tuple[int, str, int]:
|
||||
"""Rank descending, then earliest start, then lowest pid."""
|
||||
return (-self.rank, self.started, self.pid)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ArbiterVerdict:
|
||||
"""Whether this app may arm, and why."""
|
||||
|
||||
may_arm: bool
|
||||
blocked_by: Claim | None
|
||||
reason: VerdictReason
|
||||
|
||||
|
||||
def default_runtime_dir() -> Path:
|
||||
"""Return the directory holding claims and the holder lock.
|
||||
|
||||
Prefers ``$XDG_RUNTIME_DIR`` (tmpfs, so it self-clears on reboot) and falls
|
||||
back to a per-uid temp directory when that is unset or unwritable.
|
||||
"""
|
||||
override = os.environ.get(_RUNTIME_DIR_ENV)
|
||||
if override:
|
||||
return Path(override)
|
||||
xdg = os.environ.get("XDG_RUNTIME_DIR")
|
||||
if xdg:
|
||||
return Path(xdg) / "gatelock"
|
||||
return Path(tempfile.gettempdir()) / f"gatelock-{os.getuid()}"
|
||||
|
||||
|
||||
def _try_lock(handle: IO[str]) -> bool:
|
||||
"""Try to take an exclusive non-blocking flock. True if acquired."""
|
||||
try:
|
||||
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except OSError as exc:
|
||||
if exc.errno in {errno.EACCES, errno.EAGAIN}:
|
||||
return False
|
||||
raise
|
||||
return True
|
||||
|
||||
|
||||
def _same_file(handle: IO[str], path: Path) -> bool:
|
||||
"""Whether ``path`` still names the file behind ``handle``.
|
||||
|
||||
Guards the reap below: between locking a dead app's claim and unlinking it,
|
||||
a fresh process may have recreated the same path. Comparing inodes stops us
|
||||
deleting the newcomer's claim.
|
||||
"""
|
||||
try:
|
||||
return os.fstat(handle.fileno()).st_ino == path.stat().st_ino
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def _reap(handle: IO[str], path: Path) -> None:
|
||||
"""Delete a claim whose owner has died, unless it was recreated.
|
||||
|
||||
Args:
|
||||
handle: The open handle whose lock proved the owner is gone.
|
||||
path: The claim file to remove.
|
||||
"""
|
||||
if not _same_file(handle, path):
|
||||
_logger.debug("claim %s was recreated while reaping; leaving it", path)
|
||||
return
|
||||
try:
|
||||
path.unlink()
|
||||
except OSError as exc:
|
||||
_logger.debug("could not reap stale claim %s: %s", path, exc)
|
||||
|
||||
|
||||
def _read_if_live(path: Path) -> Claim | None:
|
||||
"""Return the claim at `path` if its owner is alive; else reap it.
|
||||
|
||||
Taking the advisory lock succeeds only when nobody holds it, which means
|
||||
the owning process is gone -- so a successful lock is the proof of death,
|
||||
and the file is removed rather than returned.
|
||||
"""
|
||||
try:
|
||||
handle = path.open("r+", encoding="utf-8")
|
||||
except OSError:
|
||||
return None
|
||||
with handle:
|
||||
if _try_lock(handle):
|
||||
_reap(handle, path)
|
||||
return None
|
||||
try:
|
||||
return Claim.from_json(handle.read())
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def live_claims(claims_dir: Path) -> tuple[Claim, ...]:
|
||||
"""Every claim under `claims_dir` whose owning process is still alive.
|
||||
|
||||
Dead owners' claims are reaped as a side effect -- proving a claim is
|
||||
stale and deleting it are the same operation.
|
||||
|
||||
Args:
|
||||
claims_dir: Directory holding the `*.json` claim files.
|
||||
|
||||
Returns:
|
||||
The live claims, in arbitration order.
|
||||
"""
|
||||
if not claims_dir.is_dir():
|
||||
return ()
|
||||
claims = [
|
||||
claim
|
||||
for path in sorted(claims_dir.glob("*.json"))
|
||||
if (claim := _read_if_live(path)) is not None
|
||||
]
|
||||
return tuple(sorted(claims, key=Claim.sort_key))
|
||||
|
||||
|
||||
def read_claim_if_held(path: Path) -> Claim | None:
|
||||
"""The claim at `path`, but only while a live process still holds it.
|
||||
|
||||
Taking the advisory lock succeeds only when nobody holds it, so a
|
||||
successful lock means the screen is free and there is no holder to name.
|
||||
|
||||
Args:
|
||||
path: The holder claim file.
|
||||
|
||||
Returns:
|
||||
The holder's claim, or None if the lock was free or unreadable.
|
||||
"""
|
||||
try:
|
||||
with path.open("r+", encoding="utf-8") as handle:
|
||||
if _try_lock(handle):
|
||||
return None
|
||||
return Claim.from_json(handle.read())
|
||||
except OSError:
|
||||
return None
|
||||
@ -25,8 +25,7 @@ workout debt are not general, and are deliberately not modelled here.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import timedelta
|
||||
import json
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Any
|
||||
@ -36,85 +35,31 @@ from gatelock.log_integrity import compute_entry_hmac, verify_entry_hmac
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
from gatelock._escape_types import (
|
||||
EscapeDraft,
|
||||
EscapeHistory,
|
||||
EscapePolicy,
|
||||
_parse_iso,
|
||||
_today_iso,
|
||||
)
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_DATE_FORMAT = "%Y-%m-%d"
|
||||
# Re-exported after the 250-line split; gatelock's __init__ and the tests
|
||||
# both import these from here.
|
||||
__all__ = [
|
||||
"EscapeDraft",
|
||||
"EscapeHistory",
|
||||
"EscapePolicy",
|
||||
"EscapeTracker",
|
||||
]
|
||||
|
||||
|
||||
# The severity scale the dialog presents.
|
||||
_MIN_SEVERITY = 1
|
||||
_MAX_SEVERITY = 10
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EscapePolicy:
|
||||
"""How hard one app's escape hatch is to use.
|
||||
|
||||
Defaults mirror screen-locker's sick mode, which is the proven shape.
|
||||
|
||||
Attributes:
|
||||
name: Short identifier used in logs and the summary line.
|
||||
label: Human wording for one use, e.g. "sick day".
|
||||
budget_per_7_days: Uses allowed in a rolling week.
|
||||
budget_per_30_days: Uses allowed in a rolling month.
|
||||
budget_per_90_days: Uses allowed in a rolling quarter.
|
||||
lockout_seconds: Base wait before the hatch actually opens.
|
||||
lockout_multiplier_per_recent: Wait multiplier per use in 30 days.
|
||||
justification_min_chars: Minimum length of the written reason.
|
||||
history_review_count: How many past reasons to show back to the user.
|
||||
"""
|
||||
|
||||
name: str
|
||||
label: str
|
||||
budget_per_7_days: int = 1
|
||||
budget_per_30_days: int = 3
|
||||
budget_per_90_days: int = 10
|
||||
lockout_seconds: int = 120
|
||||
lockout_multiplier_per_recent: int = 2
|
||||
justification_min_chars: int = 120
|
||||
history_review_count: int = 10
|
||||
|
||||
|
||||
@dataclass
|
||||
class EscapeHistory:
|
||||
"""Persistent record of every use of one app's hatch."""
|
||||
|
||||
used_days: list[str] = field(default_factory=list)
|
||||
justifications: list[dict[str, Any]] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EscapeDraft:
|
||||
"""A proposed use of the hatch, before validation."""
|
||||
|
||||
reason: str
|
||||
onset: str
|
||||
severity: int
|
||||
description: str
|
||||
|
||||
|
||||
def _today_iso() -> str:
|
||||
"""Return today's date as ``YYYY-MM-DD`` (UTC)."""
|
||||
return datetime.now(tz=timezone.utc).strftime(_DATE_FORMAT)
|
||||
|
||||
|
||||
def _parse_iso(date_str: str) -> datetime | None:
|
||||
"""Parse ``YYYY-MM-DD`` into a UTC datetime, or None if unparsable.
|
||||
|
||||
An unparsable entry is *ignored* rather than fatal, but logged loudly:
|
||||
silently counting it as zero would quietly widen the budget.
|
||||
"""
|
||||
try:
|
||||
return datetime.strptime(date_str, _DATE_FORMAT).replace(tzinfo=timezone.utc)
|
||||
except ValueError as exc:
|
||||
_logger.warning(
|
||||
"escape history holds an unparsable date %r (%s) -- that entry is "
|
||||
"IGNORED when counting against the budget",
|
||||
date_str,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
class EscapeTracker:
|
||||
"""Budget, lockout and tamper-evident history for one app's hatch."""
|
||||
|
||||
|
||||
88
gatelock/gatelock/_escape_types.py
Normal file
88
gatelock/gatelock/_escape_types.py
Normal file
@ -0,0 +1,88 @@
|
||||
"""The policy, history and draft types the escape hatch works with.
|
||||
|
||||
Split from :mod:`gatelock._escape`, which keeps the tracker. Data and two date
|
||||
helpers, no I/O, so the shapes can be read without the persistence around them.
|
||||
|
||||
Re-exported from :mod:`gatelock._escape`, so existing imports keep working.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_DATE_FORMAT = "%Y-%m-%d"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EscapePolicy:
|
||||
"""How hard one app's escape hatch is to use.
|
||||
|
||||
Defaults mirror screen-locker's sick mode, which is the proven shape.
|
||||
|
||||
Attributes:
|
||||
name: Short identifier used in logs and the summary line.
|
||||
label: Human wording for one use, e.g. "sick day".
|
||||
budget_per_7_days: Uses allowed in a rolling week.
|
||||
budget_per_30_days: Uses allowed in a rolling month.
|
||||
budget_per_90_days: Uses allowed in a rolling quarter.
|
||||
lockout_seconds: Base wait before the hatch actually opens.
|
||||
lockout_multiplier_per_recent: Wait multiplier per use in 30 days.
|
||||
justification_min_chars: Minimum length of the written reason.
|
||||
history_review_count: How many past reasons to show back to the user.
|
||||
"""
|
||||
|
||||
name: str
|
||||
label: str
|
||||
budget_per_7_days: int = 1
|
||||
budget_per_30_days: int = 3
|
||||
budget_per_90_days: int = 10
|
||||
lockout_seconds: int = 120
|
||||
lockout_multiplier_per_recent: int = 2
|
||||
justification_min_chars: int = 120
|
||||
history_review_count: int = 10
|
||||
|
||||
|
||||
@dataclass
|
||||
class EscapeHistory:
|
||||
"""Persistent record of every use of one app's hatch."""
|
||||
|
||||
used_days: list[str] = field(default_factory=list)
|
||||
justifications: list[dict[str, Any]] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EscapeDraft:
|
||||
"""A proposed use of the hatch, before validation."""
|
||||
|
||||
reason: str
|
||||
onset: str
|
||||
severity: int
|
||||
description: str
|
||||
|
||||
|
||||
def _today_iso() -> str:
|
||||
"""Return today's date as ``YYYY-MM-DD`` (UTC)."""
|
||||
return datetime.now(tz=timezone.utc).strftime(_DATE_FORMAT)
|
||||
|
||||
|
||||
def _parse_iso(date_str: str) -> datetime | None:
|
||||
"""Parse ``YYYY-MM-DD`` into a UTC datetime, or None if unparsable.
|
||||
|
||||
An unparsable entry is *ignored* rather than fatal, but logged loudly:
|
||||
silently counting it as zero would quietly widen the budget.
|
||||
"""
|
||||
try:
|
||||
return datetime.strptime(date_str, _DATE_FORMAT).replace(tzinfo=timezone.utc)
|
||||
except ValueError as exc:
|
||||
_logger.warning(
|
||||
"escape history holds an unparsable date %r (%s) -- that entry is "
|
||||
"IGNORED when counting against the budget",
|
||||
date_str,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
65
gatelock/gatelock/_output_types.py
Normal file
65
gatelock/gatelock/_output_types.py
Normal file
@ -0,0 +1,65 @@
|
||||
"""The value types describing a display output and a scan of them.
|
||||
|
||||
Split from :mod:`gatelock._outputs` so the two backends
|
||||
(:mod:`gatelock._randr`, :mod:`gatelock._xrandr`) can import the types without
|
||||
importing the enumerator that uses them -- which is what would otherwise make
|
||||
the dependency circular.
|
||||
|
||||
Re-exported from :mod:`gatelock._outputs`, so existing imports keep working.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal
|
||||
|
||||
OutputSource = Literal["randr", "xrandr", "tk", "none"]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OutputRect:
|
||||
"""A rectangle in root-window coordinates."""
|
||||
|
||||
x: int
|
||||
y: int
|
||||
width: int
|
||||
height: int
|
||||
|
||||
def geometry(self) -> str:
|
||||
"""Return the Tk geometry string for this rectangle."""
|
||||
return f"{self.width}x{self.height}+{self.x}+{self.y}"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Output:
|
||||
"""A single X output and whether anything can actually be seen on it."""
|
||||
|
||||
name: str
|
||||
connected: bool
|
||||
rect: OutputRect | None
|
||||
primary: bool = False
|
||||
|
||||
@property
|
||||
def live(self) -> bool:
|
||||
"""Whether this output is connected *and* has a mode."""
|
||||
return self.connected and self.rect is not None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OutputScan:
|
||||
"""The result of one enumeration attempt.
|
||||
|
||||
``ok`` records whether enumeration itself succeeded, which is a different
|
||||
question from whether any output is live. Callers must not conflate them:
|
||||
a failed scan means "no information, change nothing", while a successful
|
||||
scan with zero live outputs means "the screens really are dark".
|
||||
"""
|
||||
|
||||
outputs: tuple[Output, ...]
|
||||
source: OutputSource
|
||||
ok: bool
|
||||
|
||||
@property
|
||||
def live(self) -> tuple[Output, ...]:
|
||||
"""The subset of outputs that are connected and have a mode."""
|
||||
return tuple(output for output in self.outputs if output.live)
|
||||
@ -25,7 +25,6 @@ precisely the degradation path that must stay tested.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import logging
|
||||
import re
|
||||
import shutil
|
||||
@ -36,56 +35,27 @@ if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
import tkinter as tk
|
||||
|
||||
# python-xlib ships no type stubs. Rather than typing its objects as ``Any``
|
||||
# (or reaching for a suppression comment, which this repo bans), these
|
||||
# protocols spell out the exact surface gatelock depends on. If a future
|
||||
# python-xlib renames one of these, the type checker says so.
|
||||
class _ScreenResources(Protocol):
|
||||
config_timestamp: int
|
||||
outputs: Sequence[int]
|
||||
|
||||
class _OutputInfo(Protocol):
|
||||
name: object
|
||||
connection: int
|
||||
crtc: int
|
||||
|
||||
class _CrtcInfo(Protocol):
|
||||
mode: int
|
||||
x: int
|
||||
y: int
|
||||
width: int
|
||||
height: int
|
||||
|
||||
class _PrimaryReply(Protocol):
|
||||
output: int
|
||||
|
||||
class _XRoot(Protocol):
|
||||
def xrandr_get_screen_resources(self) -> _ScreenResources: ...
|
||||
|
||||
def xrandr_get_output_primary(self) -> _PrimaryReply: ...
|
||||
|
||||
class _XScreen(Protocol):
|
||||
root: _XRoot
|
||||
|
||||
class _XDisplay(Protocol):
|
||||
def screen(self) -> _XScreen: ...
|
||||
|
||||
def xrandr_get_output_info(
|
||||
self, output: int, timestamp: int
|
||||
) -> _OutputInfo: ...
|
||||
|
||||
def xrandr_get_crtc_info(self, crtc: int, timestamp: int) -> _CrtcInfo: ...
|
||||
|
||||
def close(self) -> None: ...
|
||||
from gatelock._output_types import Output, OutputRect, OutputScan, OutputSource
|
||||
from gatelock._randr import RandrBackend
|
||||
from gatelock._xrandr import parse_xrandr_query, scan_xrandr
|
||||
|
||||
# Re-exported after the 250-line split, so `from gatelock._outputs import
|
||||
# Output` -- which the tests and sibling modules do -- keeps resolving.
|
||||
__all__ = [
|
||||
"Output",
|
||||
"OutputEnumerator",
|
||||
"OutputRect",
|
||||
"OutputScan",
|
||||
"RandrBackend",
|
||||
"enumerate_outputs",
|
||||
"parse_xrandr_query",
|
||||
"scan_xrandr",
|
||||
"tk_fallback_outputs",
|
||||
]
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_XRANDR_TIMEOUT_S = 5.0
|
||||
|
||||
# RandR's `connection` field: 0 is RR_Connected. Hard-coded rather than
|
||||
# imported so the constant is available without python-xlib installed.
|
||||
_RR_CONNECTED = 0
|
||||
|
||||
# Output lines start at column 0; mode lines are indented four spaces. That
|
||||
# anchor is the whole robustness story -- without it, the mode line
|
||||
@ -95,231 +65,10 @@ _OUTPUT_LINE = re.compile(
|
||||
r"^(?P<name>\S+)\s+(?P<state>connected|disconnected)\b(?P<rest>.*)$",
|
||||
re.MULTILINE,
|
||||
)
|
||||
_GEOMETRY = re.compile(r"(?P<w>\d+)x(?P<h>\d+)\+(?P<x>-?\d+)\+(?P<y>-?\d+)")
|
||||
|
||||
OutputSource = Literal["randr", "xrandr", "tk", "none"]
|
||||
"""Which backend produced a scan. Reported so logs can explain a degradation."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OutputRect:
|
||||
"""A rectangle in root-window coordinates."""
|
||||
|
||||
x: int
|
||||
y: int
|
||||
width: int
|
||||
height: int
|
||||
|
||||
def geometry(self) -> str:
|
||||
"""Return the Tk geometry string for this rectangle."""
|
||||
return f"{self.width}x{self.height}+{self.x}+{self.y}"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Output:
|
||||
"""A single X output and whether anything can actually be seen on it."""
|
||||
|
||||
name: str
|
||||
connected: bool
|
||||
rect: OutputRect | None
|
||||
primary: bool = False
|
||||
|
||||
@property
|
||||
def live(self) -> bool:
|
||||
"""Whether this output is connected *and* has a mode."""
|
||||
return self.connected and self.rect is not None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OutputScan:
|
||||
"""The result of one enumeration attempt.
|
||||
|
||||
``ok`` records whether enumeration itself succeeded, which is a different
|
||||
question from whether any output is live. Callers must not conflate them:
|
||||
a failed scan means "no information, change nothing", while a successful
|
||||
scan with zero live outputs means "the screens really are dark".
|
||||
"""
|
||||
|
||||
outputs: tuple[Output, ...]
|
||||
source: OutputSource
|
||||
ok: bool
|
||||
|
||||
@property
|
||||
def live(self) -> tuple[Output, ...]:
|
||||
"""The subset of outputs that are connected and have a mode."""
|
||||
return tuple(output for output in self.outputs if output.live)
|
||||
|
||||
|
||||
def _parse_rect(head: str) -> OutputRect | None:
|
||||
"""Parse a geometry token out of an xrandr output line's head segment."""
|
||||
match = _GEOMETRY.search(head)
|
||||
if match is None:
|
||||
return None
|
||||
width = int(match.group("w"))
|
||||
height = int(match.group("h"))
|
||||
if width <= 0 or height <= 0:
|
||||
return None
|
||||
return OutputRect(
|
||||
x=int(match.group("x")),
|
||||
y=int(match.group("y")),
|
||||
width=width,
|
||||
height=height,
|
||||
)
|
||||
|
||||
|
||||
def parse_xrandr_query(text: str) -> tuple[Output, ...]:
|
||||
"""Parse ``xrandr --query`` output into outputs.
|
||||
|
||||
Args:
|
||||
text: Raw stdout from ``xrandr --query``.
|
||||
|
||||
Returns:
|
||||
One :class:`Output` per output line, in the order xrandr listed them.
|
||||
"""
|
||||
outputs: list[Output] = []
|
||||
for match in _OUTPUT_LINE.finditer(text):
|
||||
# Everything after the first "(" is rotation/reflection vocabulary and
|
||||
# panning noise -- never geometry. Slicing it off keeps the search
|
||||
# honest.
|
||||
head = match.group("rest").split("(", 1)[0]
|
||||
outputs.append(
|
||||
Output(
|
||||
name=match.group("name"),
|
||||
connected=match.group("state") == "connected",
|
||||
rect=_parse_rect(head),
|
||||
primary="primary" in head.split(),
|
||||
)
|
||||
)
|
||||
return tuple(outputs)
|
||||
|
||||
|
||||
def _decode_name(raw: object) -> str:
|
||||
"""Normalise a RandR output name, which may arrive as bytes."""
|
||||
if isinstance(raw, bytes):
|
||||
return raw.decode("utf-8", errors="replace")
|
||||
return str(raw)
|
||||
|
||||
|
||||
class RandrBackend:
|
||||
"""A persistent X connection used to enumerate outputs via RandR.
|
||||
|
||||
Held open across scans -- the recovery loop scans every second, and opening
|
||||
a fresh X connection each time would be pure waste.
|
||||
"""
|
||||
|
||||
def __init__(self, display: _XDisplay) -> None:
|
||||
"""Wrap an already-opened ``Xlib.display.Display``."""
|
||||
self._display = display
|
||||
|
||||
@classmethod
|
||||
def create(cls) -> RandrBackend | None:
|
||||
"""Open an X connection for RandR queries, or None if unavailable."""
|
||||
try:
|
||||
from Xlib import display as xdisplay
|
||||
except ImportError:
|
||||
_logger.debug(
|
||||
"python-xlib is not installed; RandR events and RandR "
|
||||
"enumeration are unavailable, falling back to xrandr"
|
||||
)
|
||||
return None
|
||||
try:
|
||||
return cls(xdisplay.Display())
|
||||
except (OSError, ValueError) as exc:
|
||||
_logger.warning("could not open an X display for RandR: %s", exc)
|
||||
return None
|
||||
|
||||
def close(self) -> None:
|
||||
"""Close the underlying X connection, ignoring teardown errors."""
|
||||
try:
|
||||
self._display.close()
|
||||
except (OSError, ValueError, AttributeError) as exc:
|
||||
_logger.debug("ignoring error while closing RandR display: %s", exc)
|
||||
|
||||
def scan(self) -> tuple[Output, ...] | None:
|
||||
"""Enumerate outputs, or None if the RandR query failed."""
|
||||
try:
|
||||
return self._scan()
|
||||
except (OSError, ValueError, KeyError, AttributeError, TypeError) as exc:
|
||||
_logger.warning("RandR enumeration failed (%s); falling back", exc)
|
||||
return None
|
||||
|
||||
def _scan(self) -> tuple[Output, ...]:
|
||||
"""Enumerate outputs via RandR. Raises on any protocol problem."""
|
||||
root = self._display.screen().root
|
||||
resources = root.xrandr_get_screen_resources()
|
||||
timestamp = resources.config_timestamp
|
||||
primary_id = self._primary_output_id(root)
|
||||
|
||||
outputs: list[Output] = []
|
||||
for output_id in resources.outputs:
|
||||
info = self._display.xrandr_get_output_info(output_id, timestamp)
|
||||
outputs.append(
|
||||
Output(
|
||||
name=_decode_name(info.name),
|
||||
connected=info.connection == _RR_CONNECTED,
|
||||
rect=self._crtc_rect(info.crtc, timestamp),
|
||||
primary=output_id == primary_id,
|
||||
)
|
||||
)
|
||||
return tuple(outputs)
|
||||
|
||||
def _primary_output_id(self, root: _XRoot) -> int | None:
|
||||
"""Return the primary output's id, or None when RandR won't say."""
|
||||
try:
|
||||
return root.xrandr_get_output_primary().output
|
||||
except (OSError, ValueError, KeyError, AttributeError, TypeError):
|
||||
return None
|
||||
|
||||
def _crtc_rect(self, crtc: int, timestamp: int) -> OutputRect | None:
|
||||
"""Return the CRTC's rectangle, or None when there is no mode.
|
||||
|
||||
``crtc == 0`` means no CRTC is assigned and ``mode == 0`` means a CRTC
|
||||
exists without a mode. Either one is the dark-monitor case.
|
||||
"""
|
||||
if not crtc:
|
||||
return None
|
||||
info = self._display.xrandr_get_crtc_info(crtc, timestamp)
|
||||
if not info.mode or info.width <= 0 or info.height <= 0:
|
||||
return None
|
||||
return OutputRect(x=info.x, y=info.y, width=info.width, height=info.height)
|
||||
|
||||
|
||||
def scan_xrandr() -> tuple[Output, ...] | None:
|
||||
"""Enumerate outputs by shelling out to ``xrandr --query``.
|
||||
|
||||
Returns:
|
||||
The parsed outputs, or None if xrandr is missing, failed, timed out or
|
||||
produced nothing parseable.
|
||||
"""
|
||||
binary = shutil.which("xrandr")
|
||||
if binary is None:
|
||||
_logger.warning("xrandr is not on PATH; cannot enumerate outputs")
|
||||
return None
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
[binary, "--query"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=_XRANDR_TIMEOUT_S,
|
||||
check=False,
|
||||
)
|
||||
except (subprocess.TimeoutExpired, OSError) as exc:
|
||||
_logger.warning("xrandr --query failed to run: %s", exc)
|
||||
return None
|
||||
if completed.returncode != 0:
|
||||
_logger.warning(
|
||||
"xrandr --query exited %d: %s",
|
||||
completed.returncode,
|
||||
completed.stderr.strip(),
|
||||
)
|
||||
return None
|
||||
outputs = parse_xrandr_query(completed.stdout)
|
||||
if not outputs:
|
||||
_logger.warning("xrandr --query produced no parseable output lines")
|
||||
return None
|
||||
return outputs
|
||||
|
||||
|
||||
def tk_fallback_outputs(root: tk.Misc) -> tuple[Output, ...]:
|
||||
"""Synthesise one output covering the whole X screen.
|
||||
|
||||
|
||||
157
gatelock/gatelock/_randr.py
Normal file
157
gatelock/gatelock/_randr.py
Normal file
@ -0,0 +1,157 @@
|
||||
"""The python-xlib RandR backend: instant output-change events.
|
||||
|
||||
Split from :mod:`gatelock._outputs`, which keeps the value types and the
|
||||
xrandr-subprocess path. python-xlib is an optional dependency -- without it
|
||||
the lock still detects output changes, just by polling -- so everything that
|
||||
touches it lives here, behind :meth:`RandrBackend.create`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Protocol
|
||||
|
||||
from gatelock._output_types import Output, OutputRect
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
# python-xlib ships no type stubs. Rather than typing its objects as ``Any``
|
||||
# (or reaching for a suppression comment, which this repo bans), these
|
||||
# protocols spell out the exact surface gatelock depends on. If a future
|
||||
# python-xlib renames one of these, the type checker says so.
|
||||
class _ScreenResources(Protocol):
|
||||
config_timestamp: int
|
||||
outputs: Sequence[int]
|
||||
|
||||
class _OutputInfo(Protocol):
|
||||
name: object
|
||||
connection: int
|
||||
crtc: int
|
||||
|
||||
class _CrtcInfo(Protocol):
|
||||
mode: int
|
||||
x: int
|
||||
y: int
|
||||
width: int
|
||||
height: int
|
||||
|
||||
class _PrimaryReply(Protocol):
|
||||
output: int
|
||||
|
||||
class _XRoot(Protocol):
|
||||
def xrandr_get_screen_resources(self) -> _ScreenResources: ...
|
||||
|
||||
def xrandr_get_output_primary(self) -> _PrimaryReply: ...
|
||||
|
||||
class _XScreen(Protocol):
|
||||
root: _XRoot
|
||||
|
||||
class _XDisplay(Protocol):
|
||||
def screen(self) -> _XScreen: ...
|
||||
|
||||
def xrandr_get_output_info(
|
||||
self, output: int, timestamp: int
|
||||
) -> _OutputInfo: ...
|
||||
|
||||
def xrandr_get_crtc_info(self, crtc: int, timestamp: int) -> _CrtcInfo: ...
|
||||
|
||||
def close(self) -> None: ...
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
# RandR's `connection` field: 0 is RR_Connected. Hard-coded rather than
|
||||
# imported so the constant is available without python-xlib installed.
|
||||
_RR_CONNECTED = 0
|
||||
|
||||
def _decode_name(raw: object) -> str:
|
||||
"""Normalise a RandR output name, which may arrive as bytes."""
|
||||
if isinstance(raw, bytes):
|
||||
return raw.decode("utf-8", errors="replace")
|
||||
return str(raw)
|
||||
|
||||
|
||||
class RandrBackend:
|
||||
"""A persistent X connection used to enumerate outputs via RandR.
|
||||
|
||||
Held open across scans -- the recovery loop scans every second, and opening
|
||||
a fresh X connection each time would be pure waste.
|
||||
"""
|
||||
|
||||
def __init__(self, display: _XDisplay) -> None:
|
||||
"""Wrap an already-opened ``Xlib.display.Display``."""
|
||||
self._display = display
|
||||
|
||||
@classmethod
|
||||
def create(cls) -> RandrBackend | None:
|
||||
"""Open an X connection for RandR queries, or None if unavailable."""
|
||||
try:
|
||||
from Xlib import display as xdisplay
|
||||
except ImportError:
|
||||
_logger.debug(
|
||||
"python-xlib is not installed; RandR events and RandR "
|
||||
"enumeration are unavailable, falling back to xrandr"
|
||||
)
|
||||
return None
|
||||
try:
|
||||
return cls(xdisplay.Display())
|
||||
except (OSError, ValueError) as exc:
|
||||
_logger.warning("could not open an X display for RandR: %s", exc)
|
||||
return None
|
||||
|
||||
def close(self) -> None:
|
||||
"""Close the underlying X connection, ignoring teardown errors."""
|
||||
try:
|
||||
self._display.close()
|
||||
except (OSError, ValueError, AttributeError) as exc:
|
||||
_logger.debug("ignoring error while closing RandR display: %s", exc)
|
||||
|
||||
def scan(self) -> tuple[Output, ...] | None:
|
||||
"""Enumerate outputs, or None if the RandR query failed."""
|
||||
try:
|
||||
return self._scan()
|
||||
except (OSError, ValueError, KeyError, AttributeError, TypeError) as exc:
|
||||
_logger.warning("RandR enumeration failed (%s); falling back", exc)
|
||||
return None
|
||||
|
||||
def _scan(self) -> tuple[Output, ...]:
|
||||
"""Enumerate outputs via RandR. Raises on any protocol problem."""
|
||||
root = self._display.screen().root
|
||||
resources = root.xrandr_get_screen_resources()
|
||||
timestamp = resources.config_timestamp
|
||||
primary_id = self._primary_output_id(root)
|
||||
|
||||
outputs: list[Output] = []
|
||||
for output_id in resources.outputs:
|
||||
info = self._display.xrandr_get_output_info(output_id, timestamp)
|
||||
outputs.append(
|
||||
Output(
|
||||
name=_decode_name(info.name),
|
||||
connected=info.connection == _RR_CONNECTED,
|
||||
rect=self._crtc_rect(info.crtc, timestamp),
|
||||
primary=output_id == primary_id,
|
||||
)
|
||||
)
|
||||
return tuple(outputs)
|
||||
|
||||
def _primary_output_id(self, root: _XRoot) -> int | None:
|
||||
"""Return the primary output's id, or None when RandR won't say."""
|
||||
try:
|
||||
return root.xrandr_get_output_primary().output
|
||||
except (OSError, ValueError, KeyError, AttributeError, TypeError):
|
||||
return None
|
||||
|
||||
def _crtc_rect(self, crtc: int, timestamp: int) -> OutputRect | None:
|
||||
"""Return the CRTC's rectangle, or None when there is no mode.
|
||||
|
||||
``crtc == 0`` means no CRTC is assigned and ``mode == 0`` means a CRTC
|
||||
exists without a mode. Either one is the dark-monitor case.
|
||||
"""
|
||||
if not crtc:
|
||||
return None
|
||||
info = self._display.xrandr_get_crtc_info(crtc, timestamp)
|
||||
if not info.mode or info.width <= 0 or info.height <= 0:
|
||||
return None
|
||||
return OutputRect(x=info.x, y=info.y, width=info.width, height=info.height)
|
||||
|
||||
|
||||
112
gatelock/gatelock/_xrandr.py
Normal file
112
gatelock/gatelock/_xrandr.py
Normal file
@ -0,0 +1,112 @@
|
||||
"""Reading outputs by shelling out to `xrandr --query`.
|
||||
|
||||
Split from :mod:`gatelock._outputs`, which keeps the value types and the
|
||||
enumerator that picks a source. This is the fallback path: slower than the
|
||||
RandR backend in :mod:`gatelock._randr` and it cannot deliver change events,
|
||||
but it needs no optional dependency, so it is what runs on a bare install.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
from gatelock._output_types import Output, OutputRect
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
_XRANDR_TIMEOUT_S = 5.0
|
||||
|
||||
# Output lines start at column 0; mode lines are indented four spaces. That
|
||||
# anchor is the whole robustness story -- without it, the mode line
|
||||
# " 2560x1440 59.95*+" parses as a geometry and every modeless output
|
||||
# silently looks live.
|
||||
_OUTPUT_LINE = re.compile(
|
||||
r"^(?P<name>\S+)\s+(?P<state>connected|disconnected)\b(?P<rest>.*)$",
|
||||
re.MULTILINE,
|
||||
)
|
||||
_GEOMETRY = re.compile(r"(?P<w>\d+)x(?P<h>\d+)\+(?P<x>-?\d+)\+(?P<y>-?\d+)")
|
||||
|
||||
_GEOMETRY = re.compile(r"(?P<w>\d+)x(?P<h>\d+)\+(?P<x>-?\d+)\+(?P<y>-?\d+)")
|
||||
|
||||
def _parse_rect(head: str) -> OutputRect | None:
|
||||
"""Parse a geometry token out of an xrandr output line's head segment."""
|
||||
match = _GEOMETRY.search(head)
|
||||
if match is None:
|
||||
return None
|
||||
width = int(match.group("w"))
|
||||
height = int(match.group("h"))
|
||||
if width <= 0 or height <= 0:
|
||||
return None
|
||||
return OutputRect(
|
||||
x=int(match.group("x")),
|
||||
y=int(match.group("y")),
|
||||
width=width,
|
||||
height=height,
|
||||
)
|
||||
|
||||
|
||||
def parse_xrandr_query(text: str) -> tuple[Output, ...]:
|
||||
"""Parse ``xrandr --query`` output into outputs.
|
||||
|
||||
Args:
|
||||
text: Raw stdout from ``xrandr --query``.
|
||||
|
||||
Returns:
|
||||
One :class:`Output` per output line, in the order xrandr listed them.
|
||||
"""
|
||||
outputs: list[Output] = []
|
||||
for match in _OUTPUT_LINE.finditer(text):
|
||||
# Everything after the first "(" is rotation/reflection vocabulary and
|
||||
# panning noise -- never geometry. Slicing it off keeps the search
|
||||
# honest.
|
||||
head = match.group("rest").split("(", 1)[0]
|
||||
outputs.append(
|
||||
Output(
|
||||
name=match.group("name"),
|
||||
connected=match.group("state") == "connected",
|
||||
rect=_parse_rect(head),
|
||||
primary="primary" in head.split(),
|
||||
)
|
||||
)
|
||||
return tuple(outputs)
|
||||
|
||||
|
||||
def scan_xrandr() -> tuple[Output, ...] | None:
|
||||
"""Enumerate outputs by shelling out to ``xrandr --query``.
|
||||
|
||||
Returns:
|
||||
The parsed outputs, or None if xrandr is missing, failed, timed out or
|
||||
produced nothing parseable.
|
||||
"""
|
||||
binary = shutil.which("xrandr")
|
||||
if binary is None:
|
||||
_logger.warning("xrandr is not on PATH; cannot enumerate outputs")
|
||||
return None
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
[binary, "--query"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=_XRANDR_TIMEOUT_S,
|
||||
check=False,
|
||||
)
|
||||
except (subprocess.TimeoutExpired, OSError) as exc:
|
||||
_logger.warning("xrandr --query failed to run: %s", exc)
|
||||
return None
|
||||
if completed.returncode != 0:
|
||||
_logger.warning(
|
||||
"xrandr --query exited %d: %s",
|
||||
completed.returncode,
|
||||
completed.stderr.strip(),
|
||||
)
|
||||
return None
|
||||
outputs = parse_xrandr_query(completed.stdout)
|
||||
if not outputs:
|
||||
_logger.warning("xrandr --query produced no parseable output lines")
|
||||
return None
|
||||
return outputs
|
||||
|
||||
|
||||
@ -73,7 +73,7 @@ def _hermetic(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Generator[None
|
||||
monkeypatch.setenv("GATELOCK_RUNTIME_DIR", str(tmp_path / "runtime"))
|
||||
with (
|
||||
patch("gatelock._surfaces.tk.Toplevel", side_effect=make_toplevel),
|
||||
patch("gatelock._outputs.RandrBackend.create", return_value=None),
|
||||
patch("gatelock._randr.RandrBackend.create", return_value=None),
|
||||
patch("gatelock._outputs.scan_xrandr", return_value=DEFAULT_OUTPUTS),
|
||||
patch("gatelock._detect._RandrEventSource.start", return_value=False),
|
||||
patch("gatelock._vt.shutil.which", return_value="/usr/bin/setxkbmap"),
|
||||
|
||||
@ -13,13 +13,12 @@ from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from gatelock._claims import _same_file, _try_lock
|
||||
from gatelock._arbiter import (
|
||||
RANK_SCREEN_LOCKER,
|
||||
RANK_WAKE_ALARM,
|
||||
Arbiter,
|
||||
Claim,
|
||||
_same_file,
|
||||
_try_lock,
|
||||
default_runtime_dir,
|
||||
grab_strength,
|
||||
)
|
||||
@ -207,7 +206,7 @@ class TestTryLock:
|
||||
exc = OSError()
|
||||
exc.errno = errno.ENOSPC
|
||||
with (
|
||||
patch("gatelock._arbiter.fcntl.flock", side_effect=exc),
|
||||
patch("gatelock._claims.fcntl.flock", side_effect=exc),
|
||||
pytest.raises(OSError, match=r"^$"),
|
||||
):
|
||||
_try_lock(handle)
|
||||
|
||||
@ -109,7 +109,7 @@ class TestPublishAndLiveClaims:
|
||||
"""A claim recreated between lock and unlink is not deleted."""
|
||||
dead = tmp_path / "rt" / "claims" / "0300-999-dead.json"
|
||||
dead.write_text(dead_claim().to_json(), "utf-8")
|
||||
with patch("gatelock._arbiter._same_file", return_value=False):
|
||||
with patch("gatelock._claims._same_file", return_value=False):
|
||||
arb.live_claims()
|
||||
assert dead.exists()
|
||||
|
||||
@ -127,7 +127,7 @@ class TestPublishAndLiveClaims:
|
||||
"""A second publish on a locked path continues unpublished."""
|
||||
arbiter = hard("a", RANK_DIET_GUARD, tmp_path / "rt")
|
||||
arbiter.publish()
|
||||
with patch("gatelock._arbiter._try_lock", return_value=False):
|
||||
with patch("gatelock._claims._try_lock", return_value=False):
|
||||
arbiter.publish() # must not raise
|
||||
arbiter.release()
|
||||
|
||||
|
||||
@ -12,12 +12,11 @@ from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from gatelock._randr import RandrBackend, _decode_name
|
||||
from gatelock._xrandr import parse_xrandr_query
|
||||
from gatelock._outputs import (
|
||||
Output,
|
||||
OutputRect,
|
||||
RandrBackend,
|
||||
_decode_name,
|
||||
parse_xrandr_query,
|
||||
)
|
||||
from gatelock._outputs import scan_xrandr as real_scan_xrandr
|
||||
|
||||
|
||||
@ -9,12 +9,12 @@ from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from gatelock._randr import RandrBackend
|
||||
from gatelock._outputs import (
|
||||
Output,
|
||||
OutputEnumerator,
|
||||
OutputRect,
|
||||
OutputScan,
|
||||
RandrBackend,
|
||||
enumerate_outputs,
|
||||
)
|
||||
|
||||
|
||||
@ -8,9 +8,9 @@ from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from gatelock._randr import RandrBackend
|
||||
from gatelock._outputs import (
|
||||
OutputRect,
|
||||
RandrBackend,
|
||||
)
|
||||
|
||||
# Bound at import, so the autouse hermetic patch (which replaces these
|
||||
|
||||
@ -69,7 +69,7 @@ class TestRemainingBranches:
|
||||
handle.read.side_effect = OSError("io error")
|
||||
with (
|
||||
patch("gatelock._arbiter.Path.open", return_value=handle),
|
||||
patch("gatelock._arbiter._try_lock", return_value=False),
|
||||
patch("gatelock._claims._try_lock", return_value=False),
|
||||
):
|
||||
assert arbiter.live_claims() == ()
|
||||
arbiter.release()
|
||||
|
||||
Loading…
Reference in New Issue
Block a user