fix(backend): make process locks cross-platform #30
5 changed files with 222 additions and 43 deletions
106
hesabixAPI/app/core/process_lock.py
Normal file
106
hesabixAPI/app/core/process_lock.py
Normal file
|
|
@ -0,0 +1,106 @@
|
||||||
|
"""Cross-platform, process-scoped file locks.
|
||||||
|
|
||||||
|
The lock is advisory and local to one host. It is intended to elect one
|
||||||
|
leader among multiple application worker processes without coupling startup to
|
||||||
|
the database.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import errno
|
||||||
|
import importlib
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import BinaryIO
|
||||||
|
|
||||||
|
|
||||||
|
def default_lock_path(filename: str) -> Path:
|
||||||
|
"""Return a writable OS-native temporary path for a lock file."""
|
||||||
|
return Path(tempfile.gettempdir()) / filename
|
||||||
|
|
||||||
|
|
||||||
|
class InterProcessFileLock:
|
||||||
|
"""Hold a non-blocking exclusive lock until :meth:`release` is called."""
|
||||||
|
|
||||||
|
def __init__(self, path: str | os.PathLike[str]):
|
||||||
|
self.path = Path(path)
|
||||||
|
self._handle: BinaryIO | None = None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def acquired(self) -> bool:
|
||||||
|
return self._handle is not None
|
||||||
|
|
||||||
|
def acquire(self) -> bool:
|
||||||
|
"""Try to acquire the lock, returning ``False`` when it is contended."""
|
||||||
|
if self._handle is not None:
|
||||||
|
return True
|
||||||
|
|
||||||
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
handle = self.path.open("a+b")
|
||||||
|
try:
|
||||||
|
# msvcrt.locking locks bytes, so make sure byte zero exists.
|
||||||
|
handle.seek(0, os.SEEK_END)
|
||||||
|
if handle.tell() == 0:
|
||||||
|
handle.write(b"\0")
|
||||||
|
handle.flush()
|
||||||
|
handle.seek(0)
|
||||||
|
|
||||||
|
if os.name == "nt":
|
||||||
|
import msvcrt
|
||||||
|
|
||||||
|
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
|
||||||
|
elif os.name == "posix":
|
||||||
|
fcntl = importlib.import_module("fcntl")
|
||||||
|
|
||||||
|
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||||
|
else:
|
||||||
|
raise RuntimeError(f"Unsupported process-lock platform: {os.name}")
|
||||||
|
except OSError as exc:
|
||||||
|
handle.close()
|
||||||
|
if exc.errno in {errno.EACCES, errno.EAGAIN, errno.EDEADLK}:
|
||||||
|
return False
|
||||||
|
raise
|
||||||
|
except Exception:
|
||||||
|
handle.close()
|
||||||
|
raise
|
||||||
|
|
||||||
|
self._handle = handle
|
||||||
|
return True
|
||||||
|
|
||||||
|
def write_owner_pid(self) -> None:
|
||||||
|
"""Write diagnostic ownership metadata without releasing the lock."""
|
||||||
|
if self._handle is None:
|
||||||
|
raise RuntimeError("Cannot write lock metadata before acquiring the lock")
|
||||||
|
self._handle.seek(0)
|
||||||
|
self._handle.truncate()
|
||||||
|
self._handle.write(f"pid={os.getpid()}\n".encode("ascii"))
|
||||||
|
self._handle.flush()
|
||||||
|
self._handle.seek(0)
|
||||||
|
|
||||||
|
def release(self) -> None:
|
||||||
|
handle = self._handle
|
||||||
|
if handle is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
self._handle = None
|
||||||
|
try:
|
||||||
|
handle.seek(0)
|
||||||
|
if os.name == "nt":
|
||||||
|
import msvcrt
|
||||||
|
|
||||||
|
msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
|
||||||
|
elif os.name == "posix":
|
||||||
|
fcntl = importlib.import_module("fcntl")
|
||||||
|
|
||||||
|
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
|
||||||
|
finally:
|
||||||
|
handle.close()
|
||||||
|
|
||||||
|
def __enter__(self) -> InterProcessFileLock:
|
||||||
|
if not self.acquire():
|
||||||
|
raise BlockingIOError(f"Lock is already held: {self.path}")
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *_args: object) -> None:
|
||||||
|
self.release()
|
||||||
|
|
@ -6,7 +6,6 @@ from app.openapi_local_docs import get_local_swagger_ui_html
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Optional, IO
|
|
||||||
|
|
||||||
from app.core.settings import get_settings
|
from app.core.settings import get_settings
|
||||||
from app.core.logging import configure_logging
|
from app.core.logging import configure_logging
|
||||||
|
|
@ -136,12 +135,13 @@ from app.core.i18n import negotiate_locale, Translator
|
||||||
from app.core.error_handlers import register_error_handlers
|
from app.core.error_handlers import register_error_handlers
|
||||||
from app.core.smart_normalizer import smart_normalize_json, SmartNormalizerConfig
|
from app.core.smart_normalizer import smart_normalize_json, SmartNormalizerConfig
|
||||||
from app.core.calendar_middleware import add_calendar_type
|
from app.core.calendar_middleware import add_calendar_type
|
||||||
|
from app.core.process_lock import InterProcessFileLock, default_lock_path
|
||||||
|
|
||||||
# Import activity log hooks برای ثبت event handlers
|
# Import activity log hooks برای ثبت event handlers
|
||||||
import adapters.db.activity_log_hooks # noqa: F401
|
import adapters.db.activity_log_hooks # noqa: F401
|
||||||
|
|
||||||
|
|
||||||
_BACKGROUND_JOBS_LOCK_FH: Optional[IO[str]] = None
|
_BACKGROUND_JOBS_LOCK: InterProcessFileLock | None = None
|
||||||
|
|
||||||
|
|
||||||
def _try_acquire_background_jobs_lock() -> bool:
|
def _try_acquire_background_jobs_lock() -> bool:
|
||||||
|
|
@ -150,40 +150,45 @@ def _try_acquire_background_jobs_lock() -> bool:
|
||||||
با uvicorn --workers هر worker جداگانه startup event را اجرا میکند؛
|
با uvicorn --workers هر worker جداگانه startup event را اجرا میکند؛
|
||||||
این lock باعث میشود فقط یکی از process ها leader شود و jobها را اجرا کند.
|
این lock باعث میشود فقط یکی از process ها leader شود و jobها را اجرا کند.
|
||||||
"""
|
"""
|
||||||
global _BACKGROUND_JOBS_LOCK_FH
|
global _BACKGROUND_JOBS_LOCK
|
||||||
|
|
||||||
# امکان خاموش کردن کامل background jobs از طریق env
|
# امکان خاموش کردن کامل background jobs از طریق env
|
||||||
enabled = os.getenv("HESABIX_BACKGROUND_JOBS_ENABLED", "true").strip().lower()
|
enabled = os.getenv("HESABIX_BACKGROUND_JOBS_ENABLED", "true").strip().lower()
|
||||||
if enabled in {"0", "false", "no", "off"}:
|
if enabled in {"0", "false", "no", "off"}:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
lock_path = os.getenv("HESABIX_BACKGROUND_JOBS_LOCKFILE", "/tmp/hesabix-background-jobs.lock")
|
if _BACKGROUND_JOBS_LOCK is not None and _BACKGROUND_JOBS_LOCK.acquired:
|
||||||
|
|
||||||
try:
|
|
||||||
import fcntl # Linux-only
|
|
||||||
except Exception:
|
|
||||||
# در محیطهایی که fcntl ندارند (مثلاً Windows) همان رفتار قبلی را نگه میداریم
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
lock_path = os.getenv(
|
||||||
|
"HESABIX_BACKGROUND_JOBS_LOCKFILE",
|
||||||
|
str(default_lock_path("hesabix-background-jobs.lock")),
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
fh = open(lock_path, "a+", encoding="utf-8")
|
lock = InterProcessFileLock(lock_path)
|
||||||
fcntl.flock(fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
if not lock.acquire():
|
||||||
fh.seek(0)
|
return False
|
||||||
fh.truncate()
|
lock.write_owner_pid()
|
||||||
fh.write(f"pid={os.getpid()}\n")
|
_BACKGROUND_JOBS_LOCK = lock
|
||||||
fh.flush()
|
|
||||||
_BACKGROUND_JOBS_LOCK_FH = fh # نگه داشتن handle برای حفظ lock
|
|
||||||
return True
|
return True
|
||||||
except Exception:
|
except Exception as exc:
|
||||||
try:
|
logging.getLogger(__name__).warning(
|
||||||
if _BACKGROUND_JOBS_LOCK_FH:
|
"Unable to acquire background-jobs process lock at %s: %s",
|
||||||
_BACKGROUND_JOBS_LOCK_FH.close()
|
lock_path,
|
||||||
except Exception:
|
exc,
|
||||||
pass
|
)
|
||||||
_BACKGROUND_JOBS_LOCK_FH = None
|
_BACKGROUND_JOBS_LOCK = None
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _release_background_jobs_lock() -> None:
|
||||||
|
global _BACKGROUND_JOBS_LOCK
|
||||||
|
if _BACKGROUND_JOBS_LOCK is not None:
|
||||||
|
_BACKGROUND_JOBS_LOCK.release()
|
||||||
|
_BACKGROUND_JOBS_LOCK = None
|
||||||
|
|
||||||
|
|
||||||
def _openapi_query_filter_section() -> str:
|
def _openapi_query_filter_section() -> str:
|
||||||
from app.openapi_query_filter_docs import OPENAPI_QUERY_FILTER_SECTION
|
from app.openapi_query_filter_docs import OPENAPI_QUERY_FILTER_SECTION
|
||||||
|
|
||||||
|
|
@ -1335,6 +1340,10 @@ def create_app() -> FastAPI:
|
||||||
|
|
||||||
asyncio.create_task(hscript_schedule_loop(60))
|
asyncio.create_task(hscript_schedule_loop(60))
|
||||||
|
|
||||||
|
@application.on_event("shutdown")
|
||||||
|
async def _release_process_locks():
|
||||||
|
_release_background_jobs_lock()
|
||||||
|
|
||||||
@application.middleware("http")
|
@application.middleware("http")
|
||||||
async def global_rate_limit_middleware(request: Request, call_next):
|
async def global_rate_limit_middleware(request: Request, call_next):
|
||||||
import time
|
import time
|
||||||
|
|
|
||||||
|
|
@ -6,10 +6,8 @@ Worker برای پردازش خودکار صف بررسی قالبهای نو
|
||||||
import asyncio
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import fcntl
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
|
@ -23,30 +21,33 @@ from adapters.db.models.business_notification import (
|
||||||
BusinessNotificationTemplate
|
BusinessNotificationTemplate
|
||||||
)
|
)
|
||||||
from app.services.ai_moderation_service import AIContentModerationService
|
from app.services.ai_moderation_service import AIContentModerationService
|
||||||
|
from app.core.process_lock import InterProcessFileLock, default_lock_path
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
# File lock برای جلوگیری از اجرای همزمان worker در چندین process
|
# File lock برای جلوگیری از اجرای همزمان worker در چندین process
|
||||||
_lock_file_path = Path("/tmp/hesabix_notification_moderation_worker.lock")
|
_lock_file_path = default_lock_path("hesabix_notification_moderation_worker.lock")
|
||||||
_worker_lock = None
|
_worker_lock: InterProcessFileLock | None = None
|
||||||
|
|
||||||
|
|
||||||
def _acquire_lock():
|
def _acquire_lock():
|
||||||
"""تلاش برای دریافت lock - فقط یک worker میتواند در هر زمان اجرا شود"""
|
"""تلاش برای دریافت lock - فقط یک worker میتواند در هر زمان اجرا شود"""
|
||||||
global _worker_lock
|
global _worker_lock
|
||||||
|
lock_path = os.getenv(
|
||||||
|
"HESABIX_NOTIFICATION_MODERATION_LOCKFILE",
|
||||||
|
str(_lock_file_path),
|
||||||
|
)
|
||||||
|
lock = InterProcessFileLock(lock_path)
|
||||||
try:
|
try:
|
||||||
_lock_file_path.parent.mkdir(parents=True, exist_ok=True)
|
if not lock.acquire():
|
||||||
_worker_lock = open(_lock_file_path, 'w')
|
return False
|
||||||
fcntl.flock(_worker_lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
lock.write_owner_pid()
|
||||||
|
_worker_lock = lock
|
||||||
return True
|
return True
|
||||||
except (IOError, OSError):
|
except Exception as exc:
|
||||||
# Lock در حال استفاده است
|
logger.warning("Unable to acquire moderation-worker lock at %s: %s", lock_path, exc)
|
||||||
if _worker_lock:
|
lock.release()
|
||||||
try:
|
_worker_lock = None
|
||||||
_worker_lock.close()
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
_worker_lock = None
|
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -54,11 +55,7 @@ def _release_lock():
|
||||||
"""آزاد کردن lock"""
|
"""آزاد کردن lock"""
|
||||||
global _worker_lock
|
global _worker_lock
|
||||||
if _worker_lock:
|
if _worker_lock:
|
||||||
try:
|
_worker_lock.release()
|
||||||
fcntl.flock(_worker_lock.fileno(), fcntl.LOCK_UN)
|
|
||||||
_worker_lock.close()
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
_worker_lock = None
|
_worker_lock = None
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,25 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from app.workers import notification_moderation_worker as worker
|
||||||
|
|
||||||
|
|
||||||
|
def test_moderation_worker_lock_is_cross_platform(
|
||||||
|
monkeypatch,
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
monkeypatch.setenv(
|
||||||
|
"HESABIX_NOTIFICATION_MODERATION_LOCKFILE",
|
||||||
|
str(tmp_path / "moderation.lock"),
|
||||||
|
)
|
||||||
|
worker._release_lock()
|
||||||
|
|
||||||
|
try:
|
||||||
|
assert worker._acquire_lock() is True
|
||||||
|
assert worker._worker_lock is not None
|
||||||
|
assert worker._worker_lock.acquired is True
|
||||||
|
finally:
|
||||||
|
worker._release_lock()
|
||||||
|
|
||||||
|
assert worker._worker_lock is None
|
||||||
42
hesabixAPI/tests/test_process_lock.py
Normal file
42
hesabixAPI/tests/test_process_lock.py
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from app.core.process_lock import InterProcessFileLock, default_lock_path
|
||||||
|
|
||||||
|
|
||||||
|
def test_default_lock_path_uses_native_temp_directory() -> None:
|
||||||
|
path = default_lock_path("hesabix-test.lock")
|
||||||
|
|
||||||
|
assert path.name == "hesabix-test.lock"
|
||||||
|
assert path.is_absolute()
|
||||||
|
|
||||||
|
|
||||||
|
def test_second_handle_cannot_acquire_held_lock(tmp_path: Path) -> None:
|
||||||
|
path = tmp_path / "leader.lock"
|
||||||
|
first = InterProcessFileLock(path)
|
||||||
|
second = InterProcessFileLock(path)
|
||||||
|
|
||||||
|
try:
|
||||||
|
assert first.acquire() is True
|
||||||
|
assert first.acquire() is True
|
||||||
|
assert second.acquire() is False
|
||||||
|
finally:
|
||||||
|
first.release()
|
||||||
|
second.release()
|
||||||
|
|
||||||
|
assert second.acquire() is True
|
||||||
|
second.release()
|
||||||
|
|
||||||
|
|
||||||
|
def test_owner_pid_is_written_without_releasing_lock(tmp_path: Path) -> None:
|
||||||
|
lock = InterProcessFileLock(tmp_path / "owner.lock")
|
||||||
|
|
||||||
|
try:
|
||||||
|
assert lock.acquire() is True
|
||||||
|
lock.write_owner_pid()
|
||||||
|
assert InterProcessFileLock(lock.path).acquire() is False
|
||||||
|
finally:
|
||||||
|
lock.release()
|
||||||
|
|
||||||
|
assert (tmp_path / "owner.lock").read_text(encoding="ascii").startswith("pid=")
|
||||||
Loading…
Reference in a new issue