"""Shared serialization and atomic-write helpers for the runtime config.""" from __future__ import annotations import json import threading from collections.abc import Mapping from pathlib import Path from typing import Any from uuid import uuid4 _LOCKS_GUARD = threading.Lock() _PATH_LOCKS: dict[str, threading.RLock] = {} def config_file_lock(path: str | Path) -> threading.RLock: """Serialize read-modify-write operations for one config path.""" # Return the native lock context manager directly -- it is cheaper than a # generator-based wrapper and needs no cleanup logic. # # (This used to also be a workaround: ``ApiError`` was a frozen dataclass, # so ``contextlib`` failed to attach ``__traceback__`` to it and replaced # any escaping ``ApiError`` with ``FrozenInstanceError``. ``ApiError`` is # no longer frozen, so ``@contextmanager`` is safe here and elsewhere.) return _lock_for_path(Path(path)) def write_text_atomic(path: str | Path, content: str) -> None: """Replace a UTF-8 text file atomically in its destination directory.""" destination = Path(path) with config_file_lock(destination): destination.parent.mkdir(parents=True, exist_ok=True) temporary = destination.with_name(f".{destination.name}.{uuid4().hex}.tmp") try: temporary.write_text(content, encoding="utf-8") temporary.replace(destination) finally: if temporary.exists(): temporary.unlink() def dump_yaml(value: Mapping[str, Any], indent: int = 0) -> str: """Serialize the simple mapping/list/scalar YAML subset used by ImageStudio.""" lines: list[str] = [] prefix = " " * indent for key, child in value.items(): if isinstance(child, Mapping): lines.append(f"{prefix}{key}:") lines.append(dump_yaml(child, indent + 2).rstrip()) elif isinstance(child, list): lines.append(f"{prefix}{key}:") for item in child: lines.append(f"{prefix} - {_format_scalar(item)}") else: lines.append(f"{prefix}{key}: {_format_scalar(child)}") return "\n".join(lines) + "\n" def _lock_for_path(path: Path) -> threading.RLock: try: key = str(path.resolve()) except OSError: key = str(path.absolute()) with _LOCKS_GUARD: lock = _PATH_LOCKS.get(key) if lock is None: lock = threading.RLock() _PATH_LOCKS[key] = lock return lock def _format_scalar(value: Any) -> str: if isinstance(value, bool): return "true" if value else "false" if value is None: return "null" if isinstance(value, (int, float)): return str(value) if isinstance(value, (Mapping, list)): # JSON flow collections are valid YAML and preserve nested adapter # objects without requiring a full YAML dependency. return json.dumps(value, ensure_ascii=False) return json.dumps(str(value), ensure_ascii=False)