| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- import json
- import os
- import shutil
- import tempfile
- import threading
- import time
- class AsyncJsonSaver:
- def __init__(self, merge_delay=0.05):
- self.merge_delay = merge_delay
- self._lock = threading.Lock()
- self._event = threading.Event()
- self._stop_event = threading.Event()
- self._pending = {}
- self._path_locks = {}
- self._worker = threading.Thread(target=self._worker_loop, daemon=True)
- self._worker.start()
- def save(self, path, data):
- with self._lock:
- self._pending[path] = data
- if path not in self._path_locks:
- self._path_locks[path] = threading.Lock()
- self._event.set()
- def flush(self, timeout=None):
- start = time.time()
- while True:
- with self._lock:
- empty = not self._pending
- if empty:
- return True
- if timeout is not None and time.time() - start > timeout:
- return False
- time.sleep(0.01)
- def shutdown(self, timeout=2.0):
- self.flush(timeout=timeout)
- self._stop_event.set()
- self._event.set()
- self._worker.join(timeout=timeout)
- def _worker_loop(self):
- while not self._stop_event.is_set():
- self._event.wait(timeout=0.1)
- if self._stop_event.is_set():
- break
- time.sleep(self.merge_delay)
- with self._lock:
- if not self._pending:
- self._event.clear()
- continue
- tasks = self._pending
- self._pending = {}
- self._event.clear()
- for path, data in tasks.items():
- try:
- self._save_json_atomic(path, data)
- except Exception as e:
- print(f"[AsyncJsonSaver] save failed: {path}, error: {e}")
- def _save_json_atomic(self, path, data):
- os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
- with self._path_locks[path]:
- backup_path = path + ".bak"
- dir_name = os.path.dirname(path) or "."
- base_name = os.path.basename(path)
- fd, temp_path = tempfile.mkstemp(
- prefix=base_name + ".",
- suffix=".tmp",
- dir=dir_name,
- text=True
- )
- try:
- with os.fdopen(fd, "w", encoding="utf-8") as f:
- json.dump(data, f, indent=4, ensure_ascii=False)
- f.flush()
- os.fsync(f.fileno())
- if os.path.exists(path):
- shutil.copy2(path, backup_path)
- os.replace(temp_path, path)
- except Exception:
- try:
- if os.path.exists(temp_path):
- os.remove(temp_path)
- except Exception:
- pass
- raise
|