File size: 2,073 Bytes
630bc9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""Identity and admission helpers for refinement requests."""

from __future__ import annotations

import hashlib
import json
from datetime import datetime, timezone
from pathlib import Path

from config.paths import JOB_DIR
from enums import JobStatus

ACTIVE_REFINEMENT_STATUSES = {JobStatus.QUEUED, JobStatus.PROCESSING}
ACTIVE_REFINEMENT_MAX_AGE_SECONDS = 20 * 60


def refinement_request_fingerprint(composite: bytes, surfaces: list[dict]) -> str:
    """Return a stable identity for the pixels and material arrangement."""
    digest = hashlib.sha256()
    digest.update(composite)
    digest.update(b"\0")
    digest.update(json.dumps(surfaces, sort_keys=True, separators=(",", ":")).encode())
    return digest.hexdigest()


def active_refinement_jobs(
    job_id: str,
    *,
    job_dir: Path = JOB_DIR,
    now: datetime | None = None,
) -> list[dict]:
    """Return recent active refinements for a conversion, newest first.

    A process restart can leave a PROCESSING JSON file behind even though no
    task exists to finish it. Ignore records older than the frontend timeout so
    they cannot permanently block a new request.
    """
    current_time = now or datetime.now(timezone.utc)
    active: list[dict] = []

    for path in job_dir.glob(f"{job_id}.refine-*.json"):
        try:
            candidate = json.loads(path.read_text())
            created_at = datetime.fromisoformat(str(candidate["createdAt"]).replace("Z", "+00:00"))
            if created_at.tzinfo is None:
                created_at = created_at.replace(tzinfo=timezone.utc)
        except (KeyError, OSError, TypeError, ValueError, json.JSONDecodeError):
            continue

        if candidate.get("jobId") != job_id:
            continue
        if candidate.get("status") not in ACTIVE_REFINEMENT_STATUSES:
            continue
        if (current_time - created_at).total_seconds() > ACTIVE_REFINEMENT_MAX_AGE_SECONDS:
            continue
        active.append(candidate)

    active.sort(key=lambda item: str(item.get("createdAt") or ""), reverse=True)
    return active