# retoor <retoor@molodetz.nl>

from __future__ import annotations

import fcntl
import logging
from pathlib import Path

logger = logging.getLogger(__name__)

_LOCK_FD = None


def acquire_web_lock(lock_path: Path) -> bool:
    # Non-blocking: web is the one Tier 3 service allowed N>1 real OS workers, so exactly one must own in-process-hub-dependent work (DbApiJobService, its query WS).
    global _LOCK_FD
    lock_path.parent.mkdir(parents=True, exist_ok=True)
    fd = open(lock_path, "w")
    try:
        fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except OSError:
        fd.close()
        return False
    _LOCK_FD = fd
    return True
