Local preservation snapshot, not a new deployment or simulation acceptance.
194 lines
7.9 KiB
Python
194 lines
7.9 KiB
Python
"""Bounded SOG editor build and resumable push over the private Core channel."""
|
|
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import time
|
|
import zipfile
|
|
from contextlib import suppress
|
|
from pathlib import Path
|
|
|
|
from local_state import write_json
|
|
from prepare_terrain import prepare_terrain
|
|
|
|
|
|
def digest(path):
|
|
with path.open("rb") as stream:
|
|
return hashlib.file_digest(stream, "sha256").hexdigest()
|
|
|
|
|
|
def verify_sog(source, output):
|
|
"""Reject accidental density or SH-band reduction before publishing a cache."""
|
|
with source.open("rb") as stream:
|
|
header = stream.read(65536).split(b"end_header", 1)[0].decode("ascii")
|
|
count = None
|
|
harmonics = 0
|
|
for line in header.splitlines():
|
|
parts = line.split()
|
|
if parts[:2] == ["element", "vertex"]:
|
|
count = int(parts[2])
|
|
if parts and parts[0] == "property" and parts[-1].startswith("f_rest_"):
|
|
harmonics += 1
|
|
bands = {0: 0, 9: 1, 24: 2, 45: 3}.get(harmonics)
|
|
with zipfile.ZipFile(output) as bundle:
|
|
metadata = json.loads(bundle.read("meta.json"))
|
|
actual_bands = metadata.get("shN", {}).get("bands", 0)
|
|
if count is None or bands is None or metadata["count"] != count or actual_bands != bands:
|
|
raise ValueError("SOG must retain the source Gaussian count and SH bands")
|
|
return {"gaussian_count": count, "sh_bands": bands}
|
|
|
|
|
|
def reuse_sog_archive(assets, world, output):
|
|
"""Bundle an admitted original SOG without another lossy encode.
|
|
|
|
The versioned registry binds the imported PLY digest to its original archive.
|
|
The archived manifest then pins every metadata/WebP byte (including SH).
|
|
"""
|
|
registry = json.loads(Path(__file__).with_name("editor-sources.json").read_text())
|
|
entry = registry.get(world["sha256"])
|
|
if not entry:
|
|
return False
|
|
manifest = assets / entry["manifest"]
|
|
if not manifest.exists():
|
|
return False
|
|
if digest(manifest) != entry["manifest_sha256"]:
|
|
raise ValueError("Original SOG archive manifest changed")
|
|
archive = json.loads(manifest.read_text(encoding="utf-8"))
|
|
if archive["source_url"] != world["source_url"]:
|
|
raise ValueError("Original SOG archive source changed")
|
|
for row in archive["files"]:
|
|
if row["path"] != "meta.json" and not re.fullmatch(r"[A-Za-z0-9_-]+\.webp", row["path"]):
|
|
raise ValueError("Invalid original SOG asset name")
|
|
path = manifest.parent / row["path"]
|
|
if path.stat().st_size != row["byte_length"] or digest(path) != row["sha256"]:
|
|
raise ValueError("Original SOG asset checksum changed")
|
|
with zipfile.ZipFile(output, "w") as bundle:
|
|
for row in archive["files"]:
|
|
info = zipfile.ZipInfo(row["path"]) # fixed timestamp, stored bytes
|
|
with (
|
|
(manifest.parent / row["path"]).open("rb") as source,
|
|
bundle.open(info, "w") as target,
|
|
):
|
|
shutil.copyfileobj(source, target)
|
|
return True
|
|
|
|
|
|
def prepare_editor(client, request, state, job):
|
|
key, world = request["key"], request["world"]
|
|
endpoint = "/worker/editor-cache/" + key
|
|
root = state.parent
|
|
target = root / "assets/editor-v2" / key
|
|
target.mkdir(parents=True, exist_ok=True)
|
|
log_path = target / "preparation.log"
|
|
last_heartbeat = -float("inf")
|
|
|
|
def pulse():
|
|
nonlocal last_heartbeat
|
|
# Asset readers call us for every bounded chunk. Keep those checkpoints
|
|
# cheap; network lease renewal depends on elapsed time, not asset size.
|
|
if time.monotonic() - last_heartbeat < 1:
|
|
return
|
|
# Heartbeats are idempotent; an expired HTTP keep-alive must not kill CPU preparation.
|
|
for attempt in range(3):
|
|
try:
|
|
client.request("/worker/heartbeat", {"instance_id": client.instance})
|
|
last_heartbeat = time.monotonic()
|
|
return
|
|
except Exception:
|
|
if attempt == 2:
|
|
raise
|
|
time.sleep(0.5)
|
|
|
|
try:
|
|
client.request(endpoint, {"action": "prepare"})
|
|
source = state / "worlds" / (world["sha256"] + ".ply")
|
|
source.parent.mkdir(exist_ok=True)
|
|
client.download(world, source, pulse=pulse)
|
|
terrain = json.loads(
|
|
prepare_terrain(root, target, world, job, pulse).read_text(encoding="utf-8-sig")
|
|
)
|
|
collider = Path(terrain["collider"])
|
|
if digest(collider) != terrain["collider_sha256"]:
|
|
raise ValueError("Collision source changed")
|
|
preview = target / "scene.sog"
|
|
metadata = target / "assets.json"
|
|
files = None
|
|
if metadata.exists():
|
|
files = json.loads(metadata.read_text())
|
|
if any(
|
|
not p.exists() or digest(p) != files[n]["sha256"]
|
|
for n, p in {"scene.sog": preview, "collision.glb": collider}.items()
|
|
):
|
|
raise ValueError("Prepared editor asset changed")
|
|
if files is None:
|
|
tool_root = root / "tools/splat-transform-3.4.0"
|
|
cli = tool_root / "node_modules/@playcanvas/splat-transform/bin/cli.mjs"
|
|
reused = reuse_sog_archive(root / "assets", world, preview)
|
|
commands = (
|
|
[]
|
|
if reused
|
|
else [
|
|
[
|
|
"node.exe",
|
|
str(cli),
|
|
"--gpu",
|
|
"cpu",
|
|
"-w",
|
|
"--max-workers",
|
|
"4",
|
|
str(source),
|
|
str(preview),
|
|
],
|
|
]
|
|
)
|
|
with log_path.open("wb") as log:
|
|
if reused:
|
|
log.write(b"Reused hash-verified original SOG archive; no re-encoding.\n")
|
|
for command in commands:
|
|
process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT)
|
|
job.assign(process)
|
|
deadline = time.monotonic() + 3600
|
|
while process.poll() is None:
|
|
pulse()
|
|
if time.monotonic() > deadline:
|
|
raise TimeoutError("Editor preparation timed out")
|
|
time.sleep(1)
|
|
if process.returncode:
|
|
raise RuntimeError(f"Editor proxy preparation failed: {process.returncode}")
|
|
write_json(target / "quality.json", verify_sog(source, preview))
|
|
files = {
|
|
name: {"sha256": digest(path), "byte_length": path.stat().st_size}
|
|
for name, path in {
|
|
"scene.sog": preview,
|
|
"collision.glb": collider,
|
|
}.items()
|
|
}
|
|
write_json(metadata, files)
|
|
status = client.request(endpoint, {"action": "manifest", "files": files})
|
|
for name, path in {"scene.sog": preview, "collision.glb": collider}.items():
|
|
with path.open("rb") as stream:
|
|
offset = status["files"][name]["uploaded_bytes"]
|
|
stream.seek(offset)
|
|
while block := stream.read(512 * 1024):
|
|
# An uncertain response resumes from the durable Core offset.
|
|
client.request(
|
|
endpoint,
|
|
{
|
|
"action": "chunk",
|
|
"name": name,
|
|
"offset": offset,
|
|
"data": base64.b64encode(block).decode(),
|
|
},
|
|
)
|
|
offset += len(block)
|
|
client.request(endpoint, {"action": "complete"})
|
|
except Exception:
|
|
import logging
|
|
|
|
logging.exception("Editor asset preparation failed")
|
|
with suppress(Exception):
|
|
client.request(endpoint, {"action": "fail"})
|