Spaces:
Running

File size: 3,196 Bytes
8a58900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
61
62
63
64
65
66
67
"""Read-only pending positions matching Worker claim_one ordering."""
from datetime import datetime, timezone
import logging
import math
import os
from pathlib import Path
import re

from src.storage import local
from src.submission.management_queue import active_requests
from src.submission.registry import _read

logger = logging.getLogger(__name__)


def waiting_positions(pending: list[dict], processing: list[dict], terminal_ids: set[str]) -> dict[str, int]:
    if not pending:
        return {}
    try:
        names = local._list_json(local.PENDING_DIR, strict=True)
        by_id = {record.get('submission_id'): record for record in pending}
        if (len(by_id) != len(pending) or any(not isinstance(sid, str) or not re.fullmatch(r'[0-9a-f]{10}', sid) for sid in by_id)
                or set(names) != {sid+'.json' for sid in by_id}):
            return {}
        processing_ids = {record.get('submission_id') for record in processing}
        maintenance = _read().get('orcid_maintenance') or {}
        if not isinstance(maintenance, dict) or maintenance.get('phase') == 'applying':
            return {}

        def blocked(record):
            return bool(maintenance and (record.get('researcher_identity_id') in
                        (maintenance.get('old_orcid'), maintenance.get('new_orcid'))
                        or record.get('hf_subject') == maintenance.get('hf_subject')))

        requests = active_requests(local.DELETE_PENDING_DIR, local.DELETE_PROCESSING_DIR,
                                   Path(local.DELETE_PENDING_DIR).parent/'complete')
        for _, request in requests:
            record = by_id.get(request.get('submission_id'))
            if (record and not blocked(request) and request.get('action') in {'cancel_pending', 'cancel_submission'}
                    and request.get('researcher_identity_id')
                    and all(record.get(key) == request.get(key) for key in ('task_name', 'researcher_identity_id'))):
                return {}
        entries = []
        for sid, record in by_id.items():
            if sid in terminal_ids or sid in processing_ids:
                return {}
            if record.get('status') not in {'pending', 'queued'} or record.get('cancel_requested_at'):
                return {}
            if blocked(record):
                continue
            submitted = None
            if 'evaluator_dispatch_ready' in record:
                try:
                    submitted = datetime.strptime(record.get('submitted_at'), '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=timezone.utc)
                except (TypeError, ValueError):
                    pass
            order = submitted.timestamp() if submitted else os.path.getmtime(os.path.join(local.PENDING_DIR, sid+'.json'))
            if not math.isfinite(order):
                return {}
            entries.append((order, sid))
        if names != local._list_json(local.PENDING_DIR, strict=True):
            return {}
        return {sid: index for index, (_, sid) in enumerate(sorted(entries), 1)}
    except (OSError, ValueError, TypeError):
        logger.warning('Waiting queue order unavailable; omitting precise positions')
        return {}