Spaces:
Running

PhysInOne-Leaderboard / src /maintenance_state.py
HAHAHA97's picture
Add read-only admin console and graceful maintenance control
4a9b55d
Raw History Blame Contribute Delete
3.16 kB
"""Versioned drain intent and Worker acknowledgements; no cross-client lock claim."""
import json
import os
from pathlib import Path
import re
import secrets
from datetime import datetime, timezone
PROTOCOL_VERSION = 1
def timestamp():
return datetime.now(timezone.utc).isoformat()
def read_object(path):
with Path(path).open(encoding="utf-8") as handle:
value = json.load(handle)
if not isinstance(value, dict):
raise ValueError("Invalid maintenance record")
return value
def write_object(path, value):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(f".{path.name}.{secrets.token_hex(8)}.tmp")
try:
with temporary.open("x", encoding="utf-8") as handle:
json.dump(value, handle, ensure_ascii=False)
handle.flush()
os.fsync(handle.fileno())
os.replace(temporary, path)
if read_object(path) != value:
raise OSError("Maintenance write confirmation failed")
finally:
temporary.unlink(missing_ok=True)
def read_control(root):
value = read_object(Path(root) / "maintenance/control.json")
if (type(value.get("version")) is not int or value.get("version") != PROTOCOL_VERSION or type(value.get("enabled")) is not bool
or not re.fullmatch(r"[a-f0-9]{32}", str(value.get("generation") or ""))):
raise ValueError("Unsupported maintenance control; new work must wait")
audit = value.get("audit", [])
if not isinstance(audit, list) or any(not isinstance(event, dict) for event in audit):
raise ValueError("Invalid maintenance audit")
lineage = {event.get("generation") for event in audit if event.get("enabled") is True}
for path in (Path(root) / "maintenance/workers").glob("*.json"):
observed = read_object(path)
if type(observed.get("version")) is not int or observed.get("version") != PROTOCOL_VERSION or type(observed.get("enabled")) is not bool:
raise ValueError("Unsupported Worker maintenance observation")
if (observed.get("enabled") is True and observed.get("generation") != value["generation"]
and observed.get("generation") not in lineage):
raise ValueError("Maintenance control predates an acknowledged drain; new work must wait")
return value
def blocked(root):
try:
return read_control(root)["enabled"]
except (OSError, ValueError, TypeError):
return True
def publish_observation(root, worker_id, operation_ids, error=None):
control = read_control(root)
identity = str(worker_id)
if not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", identity):
raise ValueError("Invalid Worker identity")
value = dict(version=PROTOCOL_VERSION, generation=control["generation"],
enabled=control["enabled"], worker_id=identity, observed_at=timestamp(),
operations=sorted(set(operation_ids)), error=error,
revision=os.environ.get("COMMIT_SHA") or os.environ.get("SPACE_COMMIT_SHA"))
write_object(Path(root) / "maintenance/workers" / f"{identity}.json", value)
return value