File size: 1,951 Bytes
ffa47ee | 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 68 69 70 | from __future__ import annotations
import hashlib
import os
import shutil
import time
from pathlib import Path
def _enabled() -> bool:
value = os.environ.get("PSI_OMNI_SQLITE_LOCAL_CACHE", "0").strip().lower()
return value not in {"0", "false", "no", "off"}
def _cache_root() -> Path:
return Path(os.environ.get("PSI_OMNI_SQLITE_LOCAL_CACHE_DIR", "/tmp/psi0_omni_sqlite_index_cache"))
def local_sqlite_path(db_path: Path) -> Path:
if not _enabled():
return db_path
db_path = Path(db_path)
try:
source_stat = db_path.stat()
except OSError:
return db_path
digest = hashlib.sha1(str(db_path.parent).encode("utf-8")).hexdigest()[:16]
local_dir = _cache_root() / digest
local_dir.mkdir(parents=True, exist_ok=True)
local_path = local_dir / db_path.name
try:
local_stat = local_path.stat()
if local_stat.st_size == source_stat.st_size and local_stat.st_mtime >= source_stat.st_mtime:
return local_path
except OSError:
pass
lock_path = local_path.with_suffix(local_path.suffix + ".lock")
while True:
try:
fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
os.close(fd)
break
except FileExistsError:
try:
local_stat = local_path.stat()
if local_stat.st_size == source_stat.st_size and local_stat.st_mtime >= source_stat.st_mtime:
return local_path
except OSError:
pass
time.sleep(0.1)
tmp_path = local_path.with_suffix(local_path.suffix + f".tmp.{os.getpid()}")
try:
shutil.copy2(db_path, tmp_path)
os.replace(tmp_path, local_path)
finally:
try:
tmp_path.unlink()
except OSError:
pass
try:
lock_path.unlink()
except OSError:
pass
return local_path
|