cmvr-visual/backend/app/core/runtime_policy.py

68 lines
2.4 KiB
Python
Raw Normal View History

"""Hot-read, operator-owned policy. Client job data never selects this file."""
import json
import math
from pathlib import Path
import time
def _read_file_policy(settings=None):
result = {"batch_window_enabled": True, "workflow_max_shots": 120, "configuration_error": None}
path = getattr(settings, "runtime_policy_file", None)
if path is None:
return result
try:
with Path(path).open("rb") as stream:
raw = stream.read(65537)
except FileNotFoundError:
return result
except OSError:
return {**result, "configuration_error": "runtime_policy_unavailable"}
try:
if len(raw) > 65536:
raise ValueError("Policy too large")
value = json.loads(raw.decode("utf-8"))
if not isinstance(value, dict) or set(value) - {
"schema_version",
"batch_window_enabled",
"workflow_max_shots",
}:
raise ValueError("Unknown policy fields")
if type(value.get("schema_version")) is not int or value["schema_version"] != 1:
raise ValueError("Unsupported schema")
if type(value.get("batch_window_enabled")) is not bool:
raise ValueError("Expected boolean switch")
max_shots = value.get("workflow_max_shots", 120)
if type(max_shots) is not int or not 1 <= max_shots <= 1000:
raise ValueError("Invalid shot limit")
except (ValueError, TypeError, UnicodeError):
return {**result, "configuration_error": "runtime_policy_invalid"}
return {
"batch_window_enabled": value["batch_window_enabled"],
"workflow_max_shots": max_shots,
"configuration_error": None,
}
def read_runtime_policy(settings=None):
policy = _read_file_policy(settings)
if not getattr(settings, "inference_remote_files", False):
return policy
error = getattr(settings, "_remote_policy_error", None)
observed = getattr(settings, "_remote_policy_observed_at", None)
if error is not None:
error = (
"runtime_policy_invalid"
if error == "runtime_policy_invalid"
else "runtime_policy_unavailable"
)
elif (
type(observed) not in (int, float)
or not math.isfinite(observed)
or not 0 <= time.monotonic() - observed <= 5
):
error = "runtime_policy_unavailable"
if error:
return {**policy, "configuration_error": error}
return policy