149 lines
5.5 KiB
Python
149 lines
5.5 KiB
Python
"""Durable explicit deletion: retain the catalog until Worker acknowledges cleanup."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import shutil
|
|
import threading
|
|
|
|
from k1link.artifacts import utc_now_iso
|
|
|
|
|
|
def write_json(path, value):
|
|
from k1link.simulation.ai_polygon.worlds import write_json as persist
|
|
|
|
persist(path, value)
|
|
descriptor = os.open(path.parent, os.O_RDONLY)
|
|
try:
|
|
os.fsync(descriptor)
|
|
finally:
|
|
os.close(descriptor)
|
|
|
|
|
|
class ProjectDeletions:
|
|
def __init__(self, service):
|
|
self.service = service
|
|
self.root = service.store.root / "deletions"
|
|
self.root.mkdir(parents=True, exist_ok=True)
|
|
self.lock = threading.RLock()
|
|
self.thread = None
|
|
self.wake = threading.Event()
|
|
|
|
def path(self, project_id):
|
|
self.service.store._project_root(project_id) # Canonical identity validation.
|
|
return self.root / f"{project_id}.json"
|
|
|
|
def contains(self, project_id):
|
|
return self.path(project_id).exists()
|
|
|
|
def list(self):
|
|
return [json.loads(p.read_text()) for p in sorted(self.root.glob("sim-*.json"))]
|
|
|
|
def request(self, project_id):
|
|
with self.lock:
|
|
if not self.contains(project_id):
|
|
project = self.service.store.get(project_id)
|
|
self.check_dependencies(project_id)
|
|
write_json(
|
|
self.path(project_id),
|
|
dict(
|
|
project_id=project_id,
|
|
name=project["name"],
|
|
requested_at=utc_now_iso(),
|
|
state="deleting",
|
|
error=None,
|
|
),
|
|
)
|
|
self.start()
|
|
self.wake.set()
|
|
|
|
def start(self):
|
|
with self.lock:
|
|
if self.thread is not None and self.thread.is_alive():
|
|
return
|
|
self.thread = threading.Thread(
|
|
target=self._run, name="simulation-deletions", daemon=True
|
|
)
|
|
self.thread.start()
|
|
|
|
def _run(self):
|
|
while True:
|
|
with self.lock:
|
|
rows = self.list()
|
|
if not rows:
|
|
self.thread = None
|
|
return
|
|
for row in rows:
|
|
self.attempt(row)
|
|
self.wake.wait(5)
|
|
self.wake.clear()
|
|
|
|
def attempt(self, row):
|
|
from k1link.simulation.projects import SimulationProjectNotFoundError
|
|
|
|
try:
|
|
try:
|
|
self.service.store.get(row["project_id"])
|
|
except SimulationProjectNotFoundError:
|
|
# Local deletion is the last step, after all remote acknowledgements.
|
|
self.path(row["project_id"]).unlink(missing_ok=True)
|
|
return
|
|
self.service.delete(row["project_id"])
|
|
self.path(row["project_id"]).unlink(missing_ok=True)
|
|
except Exception as exc:
|
|
write_json(self.path(row["project_id"]), {**row, "state": "waiting", "error": str(exc)})
|
|
|
|
def check_dependencies(self, project_id):
|
|
from k1link.simulation.projects import SimulationProjectConflictError
|
|
|
|
world_id = project_id.replace("sim-", "aiworld-", 1)
|
|
ai = self.service.store.root.parent / "ai-polygon"
|
|
# These are independent durable records, never disposable render caches.
|
|
# Refuse instead of silently orphaning a run or deleting shared evidence.
|
|
for folder in (
|
|
"runs",
|
|
"plans",
|
|
"infrastructure-jobs",
|
|
"route-preparations",
|
|
"semantic-edits",
|
|
"spatial-experience",
|
|
"urban-maps",
|
|
):
|
|
root = ai / folder
|
|
for path in root.rglob("*.json"):
|
|
if path.is_symlink():
|
|
raise SimulationProjectConflictError(
|
|
"Не удалось проверить связанные данные локации."
|
|
)
|
|
if contains_identity(path, world_id, project_id):
|
|
raise SimulationProjectConflictError(
|
|
"Локация используется в сохранённых заданиях или разметке. "
|
|
"Сначала удалите связанные задания; файлы локации сохранены."
|
|
)
|
|
|
|
def clean_local_views(self, project_id):
|
|
world_id = project_id.replace("sim-", "aiworld-", 1)
|
|
ai = self.service.store.root.parent / "ai-polygon"
|
|
for manifest in (ai / "editor-cache").glob("*/manifest.json"):
|
|
if manifest.is_symlink() or manifest.parent.is_symlink():
|
|
raise ValueError("Небезопасный путь кэша локации.")
|
|
row = json.loads(manifest.read_text())
|
|
if row.get("identity", {}).get("world_id") == world_id:
|
|
shutil.rmtree(manifest.parent)
|
|
(ai / "world-library" / f"{world_id}.json").unlink(missing_ok=True)
|
|
|
|
|
|
def contains_identity(path, *identities):
|
|
"""Scan large evidence JSON without loading geometry arrays into Core RAM."""
|
|
needles = [identity.encode("ascii") for identity in identities]
|
|
overlap = max(map(len, needles)) - 1
|
|
tail = b""
|
|
with path.open("rb") as stream:
|
|
while chunk := stream.read(64 * 1024):
|
|
window = tail + chunk
|
|
if any(needle in window for needle in needles):
|
|
return True
|
|
tail = window[-overlap:] if overlap else b""
|
|
return False
|