|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import json |
| 4 | +import logging |
| 5 | +import os |
| 6 | +import re |
| 7 | +import time |
| 8 | +import uuid |
| 9 | +from dataclasses import dataclass |
| 10 | +from pathlib import Path |
| 11 | +from typing import Any |
| 12 | + |
| 13 | +from models import MCPResponse |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | +LEASE_DIR_ENV = "UNITY_MCP_OPERATION_LEASE_DIR" |
| 18 | +LEASE_TTL_ENV = "UNITY_MCP_OPERATION_LEASE_TTL_S" |
| 19 | +DEFAULT_LEASE_TTL_S = 120.0 |
| 20 | +_SAFE_KEY_RE = re.compile(r"[^A-Za-z0-9_.@-]+") |
| 21 | + |
| 22 | + |
| 23 | +@dataclass(frozen=True) |
| 24 | +class EditorOperationLeaseInfo: |
| 25 | + instance_id: str |
| 26 | + operation: str |
| 27 | + owner: str |
| 28 | + started_unix_ms: int |
| 29 | + expires_unix_ms: int |
| 30 | + pid: int | None = None |
| 31 | + path: str | None = None |
| 32 | + |
| 33 | + |
| 34 | +@dataclass |
| 35 | +class EditorOperationLease: |
| 36 | + path: Path |
| 37 | + token: str |
| 38 | + info: EditorOperationLeaseInfo |
| 39 | + reentrant: bool = False |
| 40 | + _released: bool = False |
| 41 | + |
| 42 | + @property |
| 43 | + def instance_id(self) -> str: |
| 44 | + return self.info.instance_id |
| 45 | + |
| 46 | + @property |
| 47 | + def operation(self) -> str: |
| 48 | + return self.info.operation |
| 49 | + |
| 50 | + @property |
| 51 | + def owner(self) -> str: |
| 52 | + return self.info.owner |
| 53 | + |
| 54 | + def release(self) -> None: |
| 55 | + if self._released: |
| 56 | + return |
| 57 | + if self.reentrant: |
| 58 | + self._released = True |
| 59 | + return |
| 60 | + try: |
| 61 | + payload = _read_payload(self.path) |
| 62 | + if payload and payload.get("token") == self.token: |
| 63 | + self.path.unlink(missing_ok=True) |
| 64 | + except Exception as exc: # pragma: no cover - defensive cleanup path |
| 65 | + logger.debug("Failed to release editor operation lease %s: %r", self.path, exc) |
| 66 | + finally: |
| 67 | + self._released = True |
| 68 | + |
| 69 | + |
| 70 | +def operation_owner_from_context(ctx: Any) -> str: |
| 71 | + return f"pid:{os.getpid()}:ctx:{id(ctx)}" |
| 72 | + |
| 73 | + |
| 74 | +def operation_busy_response( |
| 75 | + lease_info: EditorOperationLeaseInfo, |
| 76 | + *, |
| 77 | + retry_after_ms: int = 2000, |
| 78 | +) -> MCPResponse: |
| 79 | + return MCPResponse( |
| 80 | + success=False, |
| 81 | + error="operation_busy", |
| 82 | + message=f"Unity editor operation already in progress: {lease_info.operation}", |
| 83 | + hint="retry", |
| 84 | + data={ |
| 85 | + "reason": "operation_busy", |
| 86 | + "retry_after_ms": int(retry_after_ms), |
| 87 | + "instance_id": lease_info.instance_id, |
| 88 | + "operation": lease_info.operation, |
| 89 | + "owner": lease_info.owner, |
| 90 | + "pid": lease_info.pid, |
| 91 | + "expires_unix_ms": lease_info.expires_unix_ms, |
| 92 | + }, |
| 93 | + ) |
| 94 | + |
| 95 | + |
| 96 | +def try_acquire_editor_operation_lease( |
| 97 | + unity_instance: str | None, |
| 98 | + operation: str, |
| 99 | + *, |
| 100 | + owner: str | None = None, |
| 101 | + ttl_s: float | None = None, |
| 102 | +) -> tuple[EditorOperationLease | None, EditorOperationLeaseInfo | None]: |
| 103 | + instance_id = unity_instance or "default" |
| 104 | + lease_dir = _operation_lease_dir() |
| 105 | + lease_dir.mkdir(parents=True, exist_ok=True) |
| 106 | + path = lease_dir / f"{_safe_lease_key(instance_id)}.json" |
| 107 | + owner = owner or f"pid:{os.getpid()}" |
| 108 | + ttl_ms = int(_lease_ttl_s(ttl_s) * 1000) |
| 109 | + |
| 110 | + while True: |
| 111 | + now_ms = _now_ms() |
| 112 | + token = uuid.uuid4().hex |
| 113 | + payload = { |
| 114 | + "instance_id": instance_id, |
| 115 | + "operation": operation, |
| 116 | + "owner": owner, |
| 117 | + "pid": os.getpid(), |
| 118 | + "token": token, |
| 119 | + "started_unix_ms": now_ms, |
| 120 | + "expires_unix_ms": now_ms + ttl_ms, |
| 121 | + } |
| 122 | + |
| 123 | + try: |
| 124 | + fd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_EXCL) |
| 125 | + except FileExistsError: |
| 126 | + existing = _read_payload(path) |
| 127 | + if _is_lease_expired(existing, path, now_ms, ttl_ms): |
| 128 | + try: |
| 129 | + path.unlink() |
| 130 | + except FileNotFoundError: |
| 131 | + continue |
| 132 | + except OSError: |
| 133 | + return None, _payload_to_info(existing, path, instance_id) |
| 134 | + continue |
| 135 | + if existing and existing.get("owner") == owner: |
| 136 | + return ( |
| 137 | + EditorOperationLease( |
| 138 | + path, |
| 139 | + str(existing.get("token") or ""), |
| 140 | + _payload_to_info(existing, path, instance_id), |
| 141 | + reentrant=True, |
| 142 | + ), |
| 143 | + None, |
| 144 | + ) |
| 145 | + return None, _payload_to_info(existing, path, instance_id) |
| 146 | + |
| 147 | + with os.fdopen(fd, "w", encoding="utf-8") as lease_file: |
| 148 | + json.dump(payload, lease_file, separators=(",", ":"), sort_keys=True) |
| 149 | + return EditorOperationLease(path, token, _payload_to_info(payload, path, instance_id)), None |
| 150 | + |
| 151 | + |
| 152 | +def _operation_lease_dir() -> Path: |
| 153 | + configured = os.environ.get(LEASE_DIR_ENV) |
| 154 | + if configured: |
| 155 | + return Path(configured) |
| 156 | + return Path.home() / ".unity-mcp" / "operation-leases" |
| 157 | + |
| 158 | + |
| 159 | +def _lease_ttl_s(ttl_s: float | None) -> float: |
| 160 | + if ttl_s is None: |
| 161 | + raw = os.environ.get(LEASE_TTL_ENV) |
| 162 | + if raw is None: |
| 163 | + return DEFAULT_LEASE_TTL_S |
| 164 | + try: |
| 165 | + ttl_s = float(raw) |
| 166 | + except ValueError: |
| 167 | + return DEFAULT_LEASE_TTL_S |
| 168 | + |
| 169 | + try: |
| 170 | + value = float(ttl_s) |
| 171 | + except (TypeError, ValueError): |
| 172 | + return DEFAULT_LEASE_TTL_S |
| 173 | + return max(0.001, min(value, 3600.0)) |
| 174 | + |
| 175 | + |
| 176 | +def _safe_lease_key(instance_id: str) -> str: |
| 177 | + key = _SAFE_KEY_RE.sub("_", instance_id).strip("._-") |
| 178 | + return key or "default" |
| 179 | + |
| 180 | + |
| 181 | +def _now_ms() -> int: |
| 182 | + return int(time.time() * 1000) |
| 183 | + |
| 184 | + |
| 185 | +def _read_payload(path: Path) -> dict[str, Any] | None: |
| 186 | + try: |
| 187 | + raw = path.read_text(encoding="utf-8") |
| 188 | + payload = json.loads(raw) |
| 189 | + return payload if isinstance(payload, dict) else None |
| 190 | + except FileNotFoundError: |
| 191 | + return None |
| 192 | + except Exception: |
| 193 | + return None |
| 194 | + |
| 195 | + |
| 196 | +def _payload_to_info( |
| 197 | + payload: dict[str, Any] | None, |
| 198 | + path: Path, |
| 199 | + fallback_instance_id: str, |
| 200 | +) -> EditorOperationLeaseInfo: |
| 201 | + payload = payload or {} |
| 202 | + started = _int_or_default(payload.get("started_unix_ms"), _mtime_ms(path)) |
| 203 | + expires = _int_or_default( |
| 204 | + payload.get("expires_unix_ms"), |
| 205 | + started + int(DEFAULT_LEASE_TTL_S * 1000), |
| 206 | + ) |
| 207 | + pid = payload.get("pid") |
| 208 | + return EditorOperationLeaseInfo( |
| 209 | + instance_id=str(payload.get("instance_id") or fallback_instance_id), |
| 210 | + operation=str(payload.get("operation") or "unknown"), |
| 211 | + owner=str(payload.get("owner") or "unknown"), |
| 212 | + started_unix_ms=started, |
| 213 | + expires_unix_ms=expires, |
| 214 | + pid=pid if isinstance(pid, int) else None, |
| 215 | + path=str(path), |
| 216 | + ) |
| 217 | + |
| 218 | + |
| 219 | +def _is_lease_expired( |
| 220 | + payload: dict[str, Any] | None, |
| 221 | + path: Path, |
| 222 | + now_ms: int, |
| 223 | + ttl_ms: int, |
| 224 | +) -> bool: |
| 225 | + if payload and isinstance(payload.get("expires_unix_ms"), int): |
| 226 | + return payload["expires_unix_ms"] <= now_ms |
| 227 | + try: |
| 228 | + return _mtime_ms(path) + ttl_ms <= now_ms |
| 229 | + except OSError: |
| 230 | + return True |
| 231 | + |
| 232 | + |
| 233 | +def _mtime_ms(path: Path) -> int: |
| 234 | + try: |
| 235 | + return int(path.stat().st_mtime * 1000) |
| 236 | + except OSError: |
| 237 | + return _now_ms() |
| 238 | + |
| 239 | + |
| 240 | +def _int_or_default(value: Any, default: int) -> int: |
| 241 | + return value if isinstance(value, int) else default |
0 commit comments