json_saver.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import json
  2. import os
  3. import shutil
  4. import tempfile
  5. import threading
  6. import time
  7. class AsyncJsonSaver:
  8. def __init__(self, merge_delay=0.05):
  9. self.merge_delay = merge_delay
  10. self._lock = threading.Lock()
  11. self._event = threading.Event()
  12. self._stop_event = threading.Event()
  13. self._pending = {}
  14. self._path_locks = {}
  15. self._worker = threading.Thread(target=self._worker_loop, daemon=True)
  16. self._worker.start()
  17. def save(self, path, data):
  18. with self._lock:
  19. self._pending[path] = data
  20. if path not in self._path_locks:
  21. self._path_locks[path] = threading.Lock()
  22. self._event.set()
  23. def flush(self, timeout=None):
  24. start = time.time()
  25. while True:
  26. with self._lock:
  27. empty = not self._pending
  28. if empty:
  29. return True
  30. if timeout is not None and time.time() - start > timeout:
  31. return False
  32. time.sleep(0.01)
  33. def shutdown(self, timeout=2.0):
  34. self.flush(timeout=timeout)
  35. self._stop_event.set()
  36. self._event.set()
  37. self._worker.join(timeout=timeout)
  38. def _worker_loop(self):
  39. while not self._stop_event.is_set():
  40. self._event.wait(timeout=0.1)
  41. if self._stop_event.is_set():
  42. break
  43. time.sleep(self.merge_delay)
  44. with self._lock:
  45. if not self._pending:
  46. self._event.clear()
  47. continue
  48. tasks = self._pending
  49. self._pending = {}
  50. self._event.clear()
  51. for path, data in tasks.items():
  52. try:
  53. self._save_json_atomic(path, data)
  54. except Exception as e:
  55. print(f"[AsyncJsonSaver] save failed: {path}, error: {e}")
  56. def _save_json_atomic(self, path, data):
  57. os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
  58. with self._path_locks[path]:
  59. backup_path = path + ".bak"
  60. dir_name = os.path.dirname(path) or "."
  61. base_name = os.path.basename(path)
  62. fd, temp_path = tempfile.mkstemp(
  63. prefix=base_name + ".",
  64. suffix=".tmp",
  65. dir=dir_name,
  66. text=True
  67. )
  68. try:
  69. with os.fdopen(fd, "w", encoding="utf-8") as f:
  70. json.dump(data, f, indent=4, ensure_ascii=False)
  71. f.flush()
  72. os.fsync(f.fileno())
  73. if os.path.exists(path):
  74. shutil.copy2(path, backup_path)
  75. os.replace(temp_path, path)
  76. except Exception:
  77. try:
  78. if os.path.exists(temp_path):
  79. os.remove(temp_path)
  80. except Exception:
  81. pass
  82. raise