Files
NqiTools/backend/app/shared/files.py
T

126 lines
3.8 KiB
Python

"""写盘规则:每个文件只有一个写入线程,替换前先写独立的临时文件。"""
from __future__ import annotations
import asyncio
import logging
import os
import threading
import time
import uuid
from concurrent.futures import Future, ThreadPoolExecutor
from pathlib import Path
logger = logging.getLogger("nqi.files")
# 杀毒、索引或同步盘会短暂打开刚写好的文件,这时替换会被拒绝,稍等即可。
REPLACE_WAITS = (0.02, 0.05, 0.1, 0.2, 0.4, 0.8)
def _noop() -> None:
return None
def _denied(exc: OSError) -> bool:
return isinstance(exc, PermissionError) or getattr(exc, "winerror", None) in {5, 32, 33}
def _key(path: Path) -> str:
return os.path.normcase(os.path.abspath(path))
def replace_file(source: Path, target: Path) -> None:
for wait in REPLACE_WAITS:
try:
os.replace(source, target)
return
except OSError as exc:
if not _denied(exc):
raise
time.sleep(wait)
os.replace(source, target)
def write_atomic(path: Path, data: bytes) -> None:
"""先写同目录下独立命名的临时文件并落盘,再替换目标。"""
temporary = path.with_name(f"{path.name}.{uuid.uuid4().hex}.tmp")
try:
with open(temporary, "wb") as handle:
handle.write(data)
handle.flush()
os.fsync(handle.fileno())
replace_file(temporary, path)
finally:
try:
temporary.unlink()
except OSError:
pass
class JobIO:
"""一个下载任务的全部文件读写都在这条线程上按提交顺序执行。"""
def __init__(self, name: str) -> None:
self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix=f"nqi-io-{name}")
async def run(self, fn, /, *args):
return await asyncio.wrap_future(self._executor.submit(fn, *args))
async def close(self) -> None:
"""等已经提交的读写全部做完,再收掉线程。"""
try:
await self.run(_noop)
finally:
self._executor.shutdown(wait=False)
class RecordWriter:
"""任务记录的唯一写入线程。同一文件只写最新一份,目录要删除时不再写。"""
def __init__(self) -> None:
self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="nqi-records")
self._lock = threading.Lock()
self._latest: dict[str, int] = {}
self._dropped: set[str] = set()
self._serial = 0
def submit(self, path: Path, data: bytes) -> Future:
key = _key(path)
with self._lock:
self._serial += 1
serial = self._serial
self._latest[key] = serial
return self._executor.submit(self._write, path, key, data, serial)
def barrier(self) -> Future:
"""在此之前提交的写入全部结束后完成。"""
return self._executor.submit(_noop)
def drop(self, directory: Path) -> Future:
with self._lock:
self._dropped.add(_key(directory))
return self.barrier()
def revive(self, directory: Path) -> None:
with self._lock:
self._dropped.discard(_key(directory))
def _write(self, path: Path, key: str, data: bytes, serial: int) -> None:
with self._lock:
if self._latest.get(key) != serial:
return
if _key(path.parent) in self._dropped:
return
try:
if path.parent.is_dir():
write_atomic(path, data)
except Exception as exc:
logger.warning("任务记录暂时写不进去,下次保存会再写 %s: %s", path, exc)
finally:
with self._lock:
if self._latest.get(key) == serial:
del self._latest[key]
RECORDS = RecordWriter()