Spaces:
Running
Running
Download src/browser_automation_agent/browser/session.py from sitcod3/dracull-agent: direct link, hf CLI and curl.
- Browser
- Download file 17.7 kB
-
https://huggingface.co/spaces/sitcod3/dracull-agent/resolve/main/src/browser_automation_agent/browser/session.py
- Command line
-
hf download hf://spaces/sitcod3/dracull-agent/src/browser_automation_agent/browser/session.py
-
curl -L -o session.py https://huggingface.co/spaces/sitcod3/dracull-agent/resolve/main/src/browser_automation_agent/browser/session.py
17.7 kB
| """BrowserSession β single owner per browser profile (plan Chapter 6 items 2-3). | |
| Two layers make duplicate ownership impossible: | |
| * **In-process** β an ``asyncio.Lock`` serializes initialization, so concurrent | |
| callers all await the SAME initialization instead of racing into two | |
| launches on one profile. | |
| * **Cross-process** β an OS-level lock file at the profile root (pid, start | |
| time, hostname, acquired_at) is created with ``O_CREAT | O_EXCL``, so a | |
| second PROCESS fails with PROFILE_LOCKED_BY_OTHER_INSTANCE instead of | |
| silently sharing a live profile (the audit reproduced exactly that | |
| duplicate-launch success before this module existed). | |
| Lock files are evidence, not garbage: a foreign or stale lock is reported | |
| with its recorded pid and start time and requires explicit user action β | |
| it is never auto-deleted. On a CLEAN shutdown the session removes ONLY its | |
| own lock file, and only when the file content still matches what it wrote. | |
| Shutdown hooks: ``atexit`` always, plus ``loop.add_signal_handler`` where the | |
| platform supports it β the Windows ``NotImplementedError`` (audit finding) is | |
| swallowed so the existing startup path keeps working; on Windows atexit and | |
| the KeyboardInterrupt path in main.py remain the cleanup route. | |
| """ | |
| from __future__ import annotations | |
| import asyncio | |
| import atexit | |
| import inspect | |
| import json | |
| import logging | |
| import os | |
| import signal | |
| import socket | |
| import sys | |
| from collections.abc import Callable | |
| from datetime import UTC, datetime, timedelta | |
| from pathlib import Path | |
| from typing import Any | |
| from .errors import ( | |
| PROFILE_LOCKED_BY_OTHER_INSTANCE, | |
| UNKNOWN, | |
| ClassifiedError, | |
| classify_os_error, | |
| redact_text, | |
| write_diagnostic_log, | |
| ) | |
| logger = logging.getLogger(__name__) | |
| LOCK_FILE_NAME = ".dracull-profile-lock.json" | |
| InitializeHook = Callable[[], Any] | |
| FinalizeHook = Callable[[], Any] | |
| def redact_path(path: str | Path) -> str: | |
| """Redacted path for user-visible surfaces (usernames never leak).""" | |
| return redact_text(str(path)) | |
| def _pid_alive(pid: int) -> bool: | |
| """Liveness of a pid without new dependencies. | |
| Windows: ctypes kernel32 ``OpenProcess``/``GetExitCodeProcess`` against | |
| STILL_ACTIVE; elsewhere ``os.kill(pid, 0)``. Unknown states count as | |
| alive β the conservative direction, because lock files are never deleted | |
| automatically anyway. | |
| """ | |
| if pid <= 0: | |
| return False | |
| if sys.platform == "win32": | |
| return _windows_pid_alive(pid) | |
| try: | |
| os.kill(pid, 0) | |
| except ProcessLookupError: | |
| return False | |
| except PermissionError: | |
| return True # exists, owned by another user | |
| except OSError: | |
| return True | |
| return True | |
| def _windows_pid_alive(pid: int) -> bool: | |
| try: | |
| import ctypes | |
| kernel32 = ctypes.windll.kernel32 | |
| PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 | |
| STILL_ACTIVE = 259 | |
| handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid) | |
| if not handle: | |
| return False | |
| exit_code = ctypes.c_ulong() | |
| try: | |
| if not kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)): | |
| return True # unknown β assume alive | |
| finally: | |
| kernel32.CloseHandle(handle) | |
| return int(exit_code.value) == STILL_ACTIVE | |
| except Exception: # noqa: BLE001 β any ctypes failure means unknown β alive | |
| return True # unknown β assume alive | |
| def _process_start_time_iso(pid: int | None = None) -> str | None: | |
| """Best-effort ISO start time of a process; None when the platform does | |
| not expose it. Informational only β lock lifetime never depends on it.""" | |
| target = os.getpid() if pid is None else pid | |
| if sys.platform == "win32": | |
| return _windows_process_start_time(target) | |
| return _linux_process_start_time(target) | |
| def _windows_process_start_time(pid: int) -> str | None: | |
| try: | |
| import ctypes | |
| from ctypes import wintypes | |
| kernel32 = ctypes.windll.kernel32 | |
| PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 | |
| handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid) | |
| if not handle: | |
| return None | |
| creation = wintypes.FILETIME() | |
| exit_time = wintypes.FILETIME() | |
| kernel_time = wintypes.FILETIME() | |
| user_time = wintypes.FILETIME() | |
| try: | |
| if not kernel32.GetProcessTimes( | |
| handle, | |
| ctypes.byref(creation), | |
| ctypes.byref(exit_time), | |
| ctypes.byref(kernel_time), | |
| ctypes.byref(user_time), | |
| ): | |
| return None | |
| finally: | |
| kernel32.CloseHandle(handle) | |
| stamp = (creation.dwHighDateTime << 32) | creation.dwLowDateTime | |
| epoch = datetime(1601, 1, 1, tzinfo=UTC) | |
| return (epoch + timedelta(microseconds=stamp // 10)).isoformat() | |
| except Exception: # noqa: BLE001 β best-effort metadata; never blocks locking | |
| return None | |
| def _linux_process_start_time(pid: int) -> str | None: | |
| try: | |
| fields = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8").rsplit(")", 1)[1].split() | |
| ticks = int(fields[19]) # starttime, overall field 22 | |
| sysconf = getattr(os, "sysconf", None) | |
| hz = int(sysconf("SC_CLK_TCK")) if callable(sysconf) else 100 | |
| btime = 0.0 | |
| for line in Path("/proc/stat").read_text(encoding="utf-8").splitlines(): | |
| if line.startswith("btime "): | |
| btime = float(line.split()[1]) | |
| break | |
| if btime <= 0: | |
| return None | |
| return datetime.fromtimestamp(btime + ticks / hz, tz=UTC).isoformat() | |
| except Exception: # noqa: BLE001 β best-effort metadata; never blocks locking | |
| return None | |
| def read_lock_info(lock_path: Path) -> dict[str, Any] | None: | |
| """Best-effort read of a lock payload; None when absent or unreadable.""" | |
| try: | |
| raw = Path(lock_path).read_text(encoding="utf-8") | |
| except (OSError, UnicodeDecodeError): | |
| return None | |
| try: | |
| data = json.loads(raw) | |
| except json.JSONDecodeError: | |
| return None | |
| return data if isinstance(data, dict) else None | |
| def _describe_owner(info: dict[str, Any] | None, lock_path: Path) -> str: | |
| if not info: | |
| return f"{redact_path(lock_path)} is present but unreadable" | |
| pid = info.get("pid") | |
| start = info.get("start_time") | |
| if isinstance(pid, int): | |
| alive = _pid_alive(pid) | |
| state = "alive" if alive else "not running" | |
| else: | |
| state = "liveness unknown" | |
| return f"owned by pid {pid} ({state}), started {start or 'unknown'}" | |
| def _locked_error(lock_path: Path, info: dict[str, Any] | None, operation: str) -> ClassifiedError: | |
| return ClassifiedError( | |
| PROFILE_LOCKED_BY_OTHER_INSTANCE, | |
| path=lock_path, | |
| operation=operation, | |
| detail=( | |
| f"{_describe_owner(info, lock_path)}. The lock file is evidence and is " | |
| "never deleted automatically β close the owning instance, or remove " | |
| "the lock explicitly once you have confirmed it is stale." | |
| ), | |
| ) | |
| class ProfileLock: | |
| """Our own OS-level profile lock; release removes ONLY matching content.""" | |
| def __init__(self, path: Path, payload: dict[str, Any]) -> None: | |
| self.path = path | |
| self.payload = payload | |
| self.released = False | |
| def release(self) -> bool: | |
| """Content-verified delete of OUR OWN lock file (clean shutdown only). | |
| Returns True when our file was removed. A file that changed hands or | |
| became unreadable is left in place as evidence β nothing foreign is | |
| ever deleted. | |
| A failed removal stays RETRYABLE: an indexer or an antivirus can hold | |
| the file briefly on Windows, and marking the lock released before the | |
| delete succeeded would leave our own lock behind forever, blocking the | |
| profile for every later run. | |
| """ | |
| if self.released: | |
| return False | |
| try: | |
| gone = not self.path.exists() | |
| except OSError: | |
| gone = False | |
| if gone: | |
| # Nothing of ours remains on disk, so there is nothing to release. | |
| self.released = True | |
| return True | |
| try: | |
| current = read_lock_info(self.path) | |
| except OSError: | |
| current = None | |
| ours = ( | |
| current is not None | |
| and current.get("pid") == self.payload.get("pid") | |
| and current.get("acquired_at") == self.payload.get("acquired_at") | |
| ) | |
| if not ours: | |
| logger.info( | |
| "Profile lock %s no longer holds our payload; leaving it untouched", | |
| self.path, | |
| ) | |
| return False | |
| try: | |
| self.path.unlink() | |
| except OSError: | |
| logger.debug("Could not remove own profile lock %s", self.path, exc_info=True) | |
| return False | |
| self.released = True | |
| return True | |
| def acquire_profile_lock( | |
| profile_dir: Path, | |
| *, | |
| operation: str = "open browser profile", | |
| ) -> ProfileLock: | |
| """Create the OS-level lock file for a profile, exclusively. | |
| Any existing lock file β live owner, stale owner, or unreadable β raises | |
| PROFILE_LOCKED_BY_OTHER_INSTANCE with the recorded pid/start time. Only a | |
| directory that this process can write to can be locked; failures classify | |
| through the shared Table 4 classifier. | |
| """ | |
| profile_dir = Path(profile_dir) | |
| try: | |
| profile_dir.mkdir(parents=True, exist_ok=True) | |
| except OSError as exc: | |
| err = classify_os_error(exc, path=profile_dir, operation=operation) | |
| write_diagnostic_log(err, exc) | |
| raise err from exc | |
| lock_path = profile_dir / LOCK_FILE_NAME | |
| existing = read_lock_info(lock_path) | |
| if existing is not None or lock_path.exists(): | |
| raise _locked_error(lock_path, existing, operation) | |
| payload: dict[str, Any] = { | |
| "pid": os.getpid(), | |
| "start_time": _process_start_time_iso(), | |
| "hostname": socket.gethostname(), | |
| "acquired_at": datetime.now(UTC).isoformat(), | |
| } | |
| try: | |
| fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY) | |
| except FileExistsError as exc: | |
| # Lost the creation race: report the winner's payload as evidence. | |
| raise _locked_error(lock_path, read_lock_info(lock_path), operation) from exc | |
| except OSError as exc: | |
| err = classify_os_error(exc, path=lock_path, operation=operation) | |
| write_diagnostic_log(err, exc) | |
| raise err from exc | |
| with os.fdopen(fd, "w", encoding="utf-8") as handle: | |
| json.dump(payload, handle) | |
| return ProfileLock(lock_path, payload) | |
| def preflight_profile_dir(profile_dir: Path) -> None: | |
| """Preflight before any launch: ensure the dir exists and accepts writes. | |
| Wraps the manager's established probe discipline (``_resolve_writable_dir``) | |
| for the directory step and adds a file-level write/delete probe with launch | |
| parity. Every failure is classified (plan Chapter 6 probe discipline); the | |
| probe file itself is always cleaned up. | |
| """ | |
| from .manager import _resolve_writable_dir # local import: manager imports this module | |
| _resolve_writable_dir(Path(profile_dir), Path(profile_dir)) | |
| probe = Path(profile_dir) / f".preflight-{os.getpid()}-{os.urandom(6).hex()}" | |
| try: | |
| fd = os.open(probe, os.O_CREAT | os.O_EXCL | os.O_WRONLY) | |
| os.close(fd) | |
| except OSError as exc: | |
| err = classify_os_error(exc, path=probe, operation="preflight write probe") | |
| write_diagnostic_log(err, exc) | |
| raise err from exc | |
| try: | |
| probe.unlink() | |
| except OSError: | |
| logger.debug("Could not remove preflight probe %s", probe, exc_info=True) | |
| class BrowserSession: | |
| """Single owner per profile: one initialization, one OS lock file.""" | |
| def __init__( | |
| self, | |
| profile_dir: Path, | |
| *, | |
| initialize: InitializeHook | None = None, | |
| finalize: FinalizeHook | None = None, | |
| ) -> None: | |
| self._profile_dir = Path(profile_dir) | |
| self._initialize = initialize | |
| self._finalize = finalize | |
| self._init_lock = asyncio.Lock() | |
| self._profile_lock: ProfileLock | None = None | |
| self._state: Any = None | |
| self._initialized = False | |
| self._shutdown = False | |
| def profile_dir(self) -> Path: | |
| return self._profile_dir | |
| def lock_path(self) -> Path: | |
| return self._profile_dir / LOCK_FILE_NAME | |
| def is_initialized(self) -> bool: | |
| return self._initialized | |
| async def ensure_initialized(self) -> Any: | |
| """Concurrent callers await the SAME initialization. | |
| Exactly one underlying ``initialize`` runs; the OS lock makes a second | |
| process fail classified instead of silently sharing the profile. | |
| """ | |
| async with self._init_lock: | |
| if self._shutdown: | |
| raise ClassifiedError( | |
| UNKNOWN, | |
| message="browser session was already shut down", | |
| operation="ensure_initialized", | |
| ) | |
| if self._initialized: | |
| return self._state | |
| self._profile_lock = acquire_profile_lock( | |
| self._profile_dir, operation="open browser profile" | |
| ) | |
| try: | |
| preflight_profile_dir(self._profile_dir) | |
| if self._initialize is not None: | |
| self._state = await self._initialize() | |
| self._initialized = True | |
| return self._state | |
| except BaseException: | |
| # We created this lock; a failed initialization is a clean | |
| # release of our own lock (content-verified, foreign untouched). | |
| self.release_lock() | |
| raise | |
| def release_lock(self) -> None: | |
| """Synchronously release OUR lock file (content-verified, idempotent).""" | |
| if self._profile_lock is not None: | |
| self._profile_lock.release() | |
| self._profile_lock = None | |
| async def shutdown(self) -> None: | |
| """Idempotent clean shutdown: finalize what init created, drop our lock. | |
| Removes nothing it did not create β the lock file is deleted only when | |
| its content still matches this session's own payload. | |
| """ | |
| if self._shutdown: | |
| return | |
| self._shutdown = True | |
| if self._finalize is not None: | |
| try: | |
| result = self._finalize() | |
| if inspect.isawaitable(result): | |
| await result | |
| except Exception: | |
| logger.debug("browser session finalize failed", exc_info=True) | |
| self.release_lock() | |
| def shutdown_sync(self) -> None: | |
| """Synchronous shutdown for atexit/signal paths (no loop required). | |
| An async finalize hook cannot run here and is skipped (logged); the | |
| lock release β the part that must never be missed β always happens. | |
| """ | |
| if self._shutdown: | |
| return | |
| self._shutdown = True | |
| if self._finalize is not None and not inspect.iscoroutinefunction(self._finalize): | |
| try: | |
| self._finalize() | |
| except Exception: | |
| logger.debug("browser session finalize failed", exc_info=True) | |
| self.release_lock() | |
| def _atexit_shutdown(session: BrowserSession) -> None: | |
| """atexit entry point: clean shutdown without a running event loop. | |
| If a loop happens to be running in this thread, only the lock release is | |
| performed synchronously β scheduling async work during interpreter exit | |
| would silently never run. | |
| """ | |
| try: | |
| asyncio.get_running_loop() | |
| except RuntimeError: | |
| pass | |
| else: | |
| session.release_lock() | |
| return | |
| try: | |
| asyncio.run(session.shutdown()) | |
| except Exception: | |
| logger.debug("atexit browser session shutdown failed", exc_info=True) | |
| session.release_lock() | |
| def install_shutdown_hooks( | |
| session: BrowserSession, | |
| *, | |
| register_signals: bool | None = None, | |
| ) -> None: | |
| """Register atexit (always) and signal handlers (where supported). | |
| Signal registration runs through ``loop.add_signal_handler`` wrapped in | |
| try/except: on Windows it raises NotImplementedError (audit finding) and | |
| is skipped, leaving atexit plus the KeyboardInterrupt path in main.py as | |
| the cleanup route. Default: signals only off-Windows. | |
| """ | |
| atexit.register(_atexit_shutdown, session) | |
| if register_signals is None: | |
| register_signals = sys.platform != "win32" | |
| if not register_signals: | |
| return | |
| try: | |
| loop = asyncio.get_running_loop() | |
| except RuntimeError: | |
| return | |
| for sig in (signal.SIGINT, signal.SIGTERM): | |
| try: | |
| loop.add_signal_handler(sig, session.shutdown_sync) | |
| except NotImplementedError: | |
| continue # Windows Proactor loop β the documented platform limit | |
| except (RuntimeError, ValueError): | |
| continue | |