statfile.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """采集进程与网页之间的两个小文件:链路状态 + 点表版本标记。
  2. 都不常驻句柄、都是"写临时文件再 rename",所以任何时刻读到的都是完整内容;
  3. 用文件而不是 DuckDB,是因为 DuckDB 的读写锁独占,采集进程一持有网页就打不开。
  4. """
  5. import json
  6. import os
  7. import time
  8. STATUS_NAME = 'status.json'
  9. VERSION_NAME = 'points.version'
  10. def atomic_write(path, text):
  11. d = os.path.dirname(path)
  12. if d:
  13. os.makedirs(d, exist_ok=True)
  14. tmp = '%s.tmp%d' % (path, os.getpid())
  15. with open(tmp, 'w', encoding='utf-8', newline='\n') as f:
  16. f.write(text)
  17. os.replace(tmp, path)
  18. return path
  19. def status_path(runtime_dir):
  20. return os.path.join(runtime_dir, STATUS_NAME)
  21. def write_status(runtime_dir, obj):
  22. return atomic_write(status_path(runtime_dir), json.dumps(obj, ensure_ascii=False, indent=1))
  23. def read_status(runtime_dir):
  24. try:
  25. with open(status_path(runtime_dir), encoding='utf-8') as f:
  26. return json.load(f)
  27. except (OSError, ValueError):
  28. return None
  29. def version_path(runtime_dir):
  30. return os.path.join(runtime_dir, VERSION_NAME)
  31. def bump_version(runtime_dir):
  32. """网页改完基础属性调用它,采集进程下一轮检查就重新加载点表。"""
  33. return atomic_write(version_path(runtime_dir), '%d\n' % time.time_ns())
  34. def read_version(runtime_dir):
  35. try:
  36. with open(version_path(runtime_dir), encoding='utf-8') as f:
  37. return f.read().strip()
  38. except OSError:
  39. return ''