← Files ClaraARCHIVED FILE

modules/studio-archive/scripts/archive_preferences.py

7.12 KB · Nov 21, 2026 · 00:11 UTC

↓ Download file

See the change to this file →

"""Owner-private archive discovery, separate from session-owned configuration."""

from __future__ import annotations

import errno
import hashlib
import json
import os
import stat
import time
from contextlib import contextmanager
from pathlib import Path
from threading import RLock, local
from typing import Any, Iterator

__all__ = [
    "PROFILE_ENV",
    "default_state_directory",
    "product_directory",
    "file_lock",
    "profile_directory",
    "read_json",
    "registry_lock",
]
PROFILE_ENV = "VERA_STUDIO_ARCHIVE_PROFILE_DIR"
_LOCK = RLock()
_HELD = local()


def product_directory() -> str:
    """Select the owning product, independently from the shared archive location."""
    if os.environ.get("LUCIA_ASSURANCE_HOST") == "1":
        return "lucia"
    if os.environ.get("CLARA_ARCHIVE_HOST") == "1":
        return "clara"
    return "vera"


def default_state_directory() -> Path:
    """Keep concurrent product sessions separate; share discovery through the profile."""
    return Path.home() / ".mparanza" / f"{product_directory().lower()}-studio-archive"


def profile_directory(state: Path) -> Path | None:
    """Explicit test/operator state stays isolated unless a profile is selected."""
    selected = os.environ.get(PROFILE_ENV, "").strip()
    default = default_state_directory()
    if selected:
        profile = Path(selected).expanduser()
    elif state.parent == default / "sessions":
        profile = Path.home() / ".mparanza" / "vera-studio-archive" / "profile"
    else:
        return None
    if not profile.is_absolute():
        raise ValueError("Archive profile directory must be absolute.")
    for parent in (profile, *profile.parents):
        if parent.is_symlink():
            raise ValueError("Archive profile cannot contain symbolic links.")
    if profile.exists():
        if not profile.is_dir():
            raise ValueError("Archive profile must be a directory.")
        if os.name == "posix" and stat.S_IMODE(profile.stat().st_mode) & 0o077:
            raise ValueError("Archive profile must be owner-private.")
    return profile


def read_json(path: Path) -> dict[str, Any] | None:
    """Read only a bounded, owner-private, single-link profile record."""
    if not path.exists() and not path.is_symlink():
        return None
    if any(parent.is_symlink() for parent in path.parents):
        raise ValueError("Archive profile record cannot have symlink ancestors.")
    before = path.lstat()
    if (
        not stat.S_ISREG(before.st_mode)
        or before.st_nlink != 1
        or before.st_size > 8 * 1024 * 1024
        or (os.name == "posix" and stat.S_IMODE(before.st_mode) & 0o077)
    ):
        raise ValueError("Archive profile record must be bounded and owner-private.")
    descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
    try:
        with os.fdopen(descriptor, "rb") as handle:
            opened = os.fstat(handle.fileno())
            content = handle.read(before.st_size + 1)
            after = os.fstat(handle.fileno())
        identity = lambda value: (
            value.st_dev,
            value.st_ino,
            value.st_size,
            value.st_mtime_ns,
            value.st_nlink,
        )
        if (
            identity(before) != identity(opened)
            or identity(before) != identity(after)
            or len(content) != before.st_size
        ):
            raise ValueError("Archive profile record changed while being read.")
        payload = json.loads(content)
    except (UnicodeError, json.JSONDecodeError) as exc:
        raise ValueError("Archive profile record is unreadable.") from exc
    if not isinstance(payload, dict):
        raise ValueError("Archive profile record must be an object.")
    return payload


def _acquire_file_lock(descriptor: int, deadline: float, label: str) -> None:
    """Wait briefly for genuine contention; never remove or steal an OS lock."""
    while True:
        try:
            if os.name == "nt":
                import msvcrt

                if os.fstat(descriptor).st_size == 0:
                    os.write(descriptor, b"0")
                os.lseek(descriptor, 0, os.SEEK_SET)
                msvcrt.locking(descriptor, msvcrt.LK_NBLCK, 1)
            else:
                import fcntl

                fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
            return
        except OSError as exc:
            if exc.errno not in {
                errno.EACCES,
                errno.EAGAIN,
                errno.EDEADLK,
                errno.EINTR,
            }:
                raise
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                raise TimeoutError(
                    f"Archive {label} is busy; retry after the other operation "
                    "finishes. No lock was removed or client changed."
                ) from exc
            time.sleep(min(0.05, remaining))


@contextmanager
def file_lock(
    path: Path, *, label: str, timeout_seconds: float = 10.0
) -> Iterator[int]:
    """Protect a bounded operation with a real, ordinary-file OS lock."""
    if any(parent.is_symlink() for parent in (path, *path.parents)):
        raise ValueError(f"Archive {label} lock cannot use symbolic links.")
    descriptor = os.open(
        path, os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0), 0o600
    )
    try:
        observed = os.fstat(descriptor)
        if not stat.S_ISREG(observed.st_mode) or observed.st_nlink != 1:
            raise ValueError(f"Archive {label} lock must be an ordinary file.")
        _acquire_file_lock(descriptor, time.monotonic() + timeout_seconds, label)
        yield descriptor
    finally:
        os.close(descriptor)


@contextmanager
def registry_lock(
    profile: Path, archive_root: Path, *, timeout_seconds: float = 10.0
) -> Iterator[Path]:
    """Serialize root-specific identity read/modify/write, never session selection."""
    root_key = hashlib.sha256(str(archive_root).encode()).hexdigest()
    directory = profile / "archives" / root_key
    deadline = time.monotonic() + timeout_seconds
    if not _LOCK.acquire(timeout=max(0.0, timeout_seconds)):
        raise TimeoutError("Archive identity registry is busy; retry later.")
    try:
        held = getattr(_HELD, "paths", set())
        if directory in held:
            yield directory
            return
        for parent in (directory, directory.parent):
            if parent.is_symlink():
                raise ValueError("Archive identity storage cannot be a symbolic link.")
        profile.mkdir(parents=True, exist_ok=True, mode=0o700)
        directory.mkdir(parents=True, exist_ok=True, mode=0o700)
        if os.name == "posix":
            for private in (directory.parent, directory):
                if stat.S_IMODE(private.stat().st_mode) != 0o700:
                    private.chmod(0o700)
        lock_path = directory / ".identities.lock"
        with file_lock(
            lock_path,
            label="identity registry",
            timeout_seconds=max(0.0, deadline - time.monotonic()),
        ):
            _HELD.paths = held | {directory}
            try:
                yield directory
            finally:
                _HELD.paths = held
    finally:
        _LOCK.release()

SHA-256: f680fb92c062bbb0ba79317b60aaace04fb4c6788f8cda1c7c28d5df1c9d8483