cmvr-visual/inference/llm_services/native_av_calibration.py

132 lines
4.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""私有操作员小样票据:源文件、请求、所有者、幂等任务与队列任务共同绑定。"""
import hashlib
import json
import math
import os
import re
import tempfile
import time
from pathlib import Path
def request_digest(task, inputs, parameters, owner, idempotency_key):
raw = json.dumps(
[task, inputs, parameters, owner, idempotency_key],
sort_keys=True,
separators=(",", ":"),
ensure_ascii=False,
allow_nan=False,
)
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def _claim(path, value, workspace):
from .store import open_confined_file
raw = json.dumps(value, sort_keys=True, separators=(",", ":")).encode()
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as stream:
temporary = Path(stream.name)
stream.write(raw)
stream.flush()
os.fsync(stream.fileno())
try:
try:
os.link(temporary, path)
except FileExistsError:
pass
with open_confined_file(path, workspace) as stream:
return stream.read(len(raw) + 1) == raw
finally:
temporary.unlink(missing_ok=True)
def admit(settings, task, inputs, parameters, owner, idempotency_key, *, job_id=None):
from .store import open_confined_file
from .video_profiles import is_native_av
if (
not isinstance(inputs, dict)
or not isinstance(parameters, dict)
or not isinstance(owner, str)
or re.fullmatch("[0-9a-f]{32}", owner) is None
or not isinstance(idempotency_key, str)
or re.fullmatch("cmvr-visual:[0-9a-f]{32}", idempotency_key) is None
or job_id is not None
and (
not isinstance(job_id, str) or re.fullmatch("[0-9a-f]{32}", job_id) is None
)
):
return False
if not (
task == "video.generate"
and is_native_av(parameters)
or task == "audio.dialogue.inspect"
and parameters.get("profile") == "dialogue-audio-v1"
and parameters.get("native_av_policy") == "native_av_v1"
):
return False
try:
digest = request_digest(task, inputs, parameters, owner, idempotency_key)
path = (
settings.app_root
/ "config"
/ "native-av-validation"
/ "calibration"
/ (digest + ".json")
)
if path.resolve() != path or path.is_symlink():
return False
with open_confined_file(path, settings.workspace_root) as stream:
# 票据只从操作员私有目录读取,上传目录与客户端参数都不能提供授权文件。
if os.name == "posix" and os.fstat(stream.fileno()).st_mode & 0o077:
return False
raw = stream.read(65537)
if len(raw) > 65536:
return False
receipt = json.loads(raw)
now = time.time()
issued, expires = receipt.get("issued_at"), receipt.get("expires_at")
if (
receipt.get("schema_version") != 1
or receipt.get("request_sha256") != digest
or receipt.get("task_type") != task
or receipt.get("profile") != parameters.get("profile")
or receipt.get("owner_id") != owner
or receipt.get("idempotency_key") != idempotency_key
or type(receipt.get("max_uses")) is not int
or receipt["max_uses"] != 1
or any(
type(v) not in (int, float) or not math.isfinite(v)
for v in (issued, expires)
)
or not now - 1800 <= issued <= now < expires <= issued + 1800
):
return False
hashes = {}
for key, name in inputs.items():
if key.endswith("_path"):
digest_file = hashlib.sha256()
with open_confined_file(name, settings.workspace_root) as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
digest_file.update(chunk)
hashes[key] = digest_file.hexdigest()
if not hashes or hashes != receipt.get("source_sha256"):
return False
binding = {
"request_sha256": digest,
"owner_id": owner,
"idempotency_key": idempotency_key,
"source_sha256": hashes,
}
if not _claim(path.with_suffix(".used"), binding, settings.workspace_root):
return False
# API的幂等键唯一指向一个任务;worker首次准入再原子绑定真实队列ID,重试只能重入同一任务。
return job_id is None or _claim(
path.with_suffix(".job"),
{**binding, "job_id": job_id},
settings.workspace_root,
)
except (OSError, ValueError, TypeError, KeyError, AttributeError):
return False