"""Private, one-shot local handoff from Italy Query discovery to Book recheck. This is a debug-only adapter. Production continues to use the existing Sentinel -> Redis -> Booker path. The file contains metadata only and is atomically claimed so a weak signal cannot trigger two local Book attempts. """ from __future__ import annotations import json import math import os import stat import time import uuid from dataclasses import dataclass from pathlib import Path PROJECT_ROOT = Path(__file__).resolve().parents[1] ITA_LOCAL_HANDOFF_ROOT = PROJECT_ROOT / "data" / "ita_local_handoff" ITA_LOCAL_SIGNAL_NAME = "query-weak-signal.json" ITA_LOCAL_SIGNAL_SCHEMA = 1 ITA_LOCAL_SIGNAL_KIND = "italy-query-weak-signal" ITA_LOCAL_SIGNAL_EVIDENCE = "booking-form" ITA_LOCAL_SIGNAL_TTL_SECONDS = 30 ITA_LOCAL_SIGNAL_MAX_BYTES = 4096 ITA_LOCAL_SIGNAL_FUTURE_SKEW_SECONDS = 5 class ItaLocalHandoffError(ValueError): """Raised when the local handoff artifact is unsafe or invalid.""" class ItaLocalSignalStaleError(ItaLocalHandoffError): """Raised after an expired signal has been atomically consumed.""" @dataclass(frozen=True) class ItaLocalWeakSignal: service_id: int routing_key: str evidence: str issued_at: float def _ensure_private_directory(path: Path) -> Path: if path.is_symlink(): raise ItaLocalHandoffError("local handoff directory must not be a symlink") try: path.mkdir(mode=0o700, parents=True, exist_ok=True) except OSError as exc: raise ItaLocalHandoffError( f"cannot create local handoff directory ({type(exc).__name__})" ) from exc if path.is_symlink() or not path.is_dir(): raise ItaLocalHandoffError( "local handoff path must be a private directory" ) if os.name == "posix": try: path.chmod(0o700) mode = stat.S_IMODE(path.stat().st_mode) except OSError as exc: raise ItaLocalHandoffError( f"cannot secure local handoff directory ({type(exc).__name__})" ) from exc if mode != 0o700: raise ItaLocalHandoffError( "local handoff directory permissions must be 700" ) return path.resolve() def _resolved_root(handoff_root: str | Path | None) -> Path: root = Path(handoff_root or ITA_LOCAL_HANDOFF_ROOT).expanduser() if not root.is_absolute(): root = PROJECT_ROOT / root return _ensure_private_directory(root) def _write_private_file(path: Path, content: bytes) -> None: temp_path = path.parent / f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp" flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL flags |= getattr(os, "O_NOFOLLOW", 0) descriptor: int | None = None try: descriptor = os.open(temp_path, flags, 0o600) if os.name == "posix": os.fchmod(descriptor, 0o600) with os.fdopen(descriptor, "wb") as handle: descriptor = None handle.write(content) handle.flush() os.fsync(handle.fileno()) os.replace(temp_path, path) if os.name == "posix": path.chmod(0o600) if stat.S_IMODE(path.stat().st_mode) != 0o600: raise ItaLocalHandoffError( "local handoff signal permissions must be 600" ) except ItaLocalHandoffError: raise except OSError as exc: raise ItaLocalHandoffError( f"cannot publish local handoff signal ({type(exc).__name__})" ) from exc finally: if descriptor is not None: os.close(descriptor) try: temp_path.unlink() except FileNotFoundError: pass except OSError: pass def publish_local_weak_signal( *, service_id: int, routing_key: str, issued_at: float | None = None, handoff_root: str | Path | None = None, ) -> Path: """Atomically publish one short-lived, metadata-only weak signal.""" if ( isinstance(service_id, bool) or not isinstance(service_id, int) or service_id <= 0 ): raise ItaLocalHandoffError("local handoff service_id must be positive") normalized_routing_key = str(routing_key or "").strip() if not normalized_routing_key: raise ItaLocalHandoffError("local handoff routing_key is required") timestamp = time.time() if issued_at is None else float(issued_at) if not math.isfinite(timestamp): raise ItaLocalHandoffError("local handoff issued_at must be finite") payload = { "schema": ITA_LOCAL_SIGNAL_SCHEMA, "kind": ITA_LOCAL_SIGNAL_KIND, "service_id": service_id, "routing_key": normalized_routing_key, "evidence": ITA_LOCAL_SIGNAL_EVIDENCE, "issued_at": timestamp, } encoded = json.dumps( payload, ensure_ascii=True, sort_keys=True, separators=(",", ":"), ).encode("utf-8") root = _resolved_root(handoff_root) signal_path = root / ITA_LOCAL_SIGNAL_NAME _write_private_file(signal_path, encoded) return signal_path def _read_claimed_payload(path: Path) -> dict: flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) descriptor: int | None = None try: descriptor = os.open(path, flags) file_stat = os.fstat(descriptor) if not stat.S_ISREG(file_stat.st_mode): raise ItaLocalHandoffError( "local handoff signal must be a regular file" ) if os.name == "posix" and stat.S_IMODE(file_stat.st_mode) != 0o600: raise ItaLocalHandoffError( "local handoff signal permissions must be 600" ) content = os.read(descriptor, ITA_LOCAL_SIGNAL_MAX_BYTES + 1) except ItaLocalHandoffError: raise except OSError as exc: raise ItaLocalHandoffError( f"cannot read local handoff signal ({type(exc).__name__})" ) from exc finally: if descriptor is not None: os.close(descriptor) if len(content) > ITA_LOCAL_SIGNAL_MAX_BYTES: raise ItaLocalHandoffError("local handoff signal is too large") try: payload = json.loads(content.decode("utf-8")) except (UnicodeDecodeError, json.JSONDecodeError) as exc: raise ItaLocalHandoffError("local handoff signal is invalid JSON") from exc if not isinstance(payload, dict): raise ItaLocalHandoffError("local handoff signal must be a JSON object") return payload def claim_local_weak_signal( *, expected_service_id: int, expected_routing_key: str, ttl_seconds: int = ITA_LOCAL_SIGNAL_TTL_SECONDS, now: float | None = None, handoff_root: str | Path | None = None, ) -> ItaLocalWeakSignal | None: """Atomically consume and validate one weak signal, or return ``None``.""" if ttl_seconds <= 0: raise ItaLocalHandoffError("local handoff ttl_seconds must be positive") root = _resolved_root(handoff_root) signal_path = root / ITA_LOCAL_SIGNAL_NAME try: signal_stat = signal_path.lstat() except FileNotFoundError: return None except OSError as exc: raise ItaLocalHandoffError( f"cannot inspect local handoff signal ({type(exc).__name__})" ) from exc if not stat.S_ISREG(signal_stat.st_mode): raise ItaLocalHandoffError("local handoff signal must be a regular file") claim_path = root / ( f".{ITA_LOCAL_SIGNAL_NAME}.{os.getpid()}.{uuid.uuid4().hex}.claim" ) try: try: os.replace(signal_path, claim_path) except FileNotFoundError: return None payload = _read_claimed_payload(claim_path) expected_keys = { "schema", "kind", "service_id", "routing_key", "evidence", "issued_at", } if set(payload) != expected_keys: raise ItaLocalHandoffError( "local handoff signal has an unsupported schema" ) if payload["schema"] != ITA_LOCAL_SIGNAL_SCHEMA: raise ItaLocalHandoffError( "local handoff signal schema version is unsupported" ) if payload["kind"] != ITA_LOCAL_SIGNAL_KIND: raise ItaLocalHandoffError("local handoff signal kind is invalid") if payload["evidence"] != ITA_LOCAL_SIGNAL_EVIDENCE: raise ItaLocalHandoffError("local handoff signal evidence is invalid") if payload["service_id"] != expected_service_id: raise ItaLocalHandoffError( "local handoff signal service_id does not match" ) if payload["routing_key"] != expected_routing_key: raise ItaLocalHandoffError( "local handoff signal routing_key does not match" ) issued_at_raw = payload["issued_at"] if isinstance(issued_at_raw, bool) or not isinstance( issued_at_raw, (int, float) ): raise ItaLocalHandoffError( "local handoff signal issued_at is invalid" ) issued_at = float(issued_at_raw) current_time = time.time() if now is None else float(now) if not math.isfinite(issued_at) or not math.isfinite(current_time): raise ItaLocalHandoffError( "local handoff signal timestamp is invalid" ) if issued_at - current_time > ITA_LOCAL_SIGNAL_FUTURE_SKEW_SECONDS: raise ItaLocalHandoffError( "local handoff signal timestamp is in the future" ) if current_time - issued_at > ttl_seconds: raise ItaLocalSignalStaleError("local handoff signal has expired") return ItaLocalWeakSignal( service_id=expected_service_id, routing_key=expected_routing_key, evidence=ITA_LOCAL_SIGNAL_EVIDENCE, issued_at=issued_at, ) finally: try: claim_path.unlink() except FileNotFoundError: pass except OSError: pass