|
| 1 | +import atexit |
| 2 | +import datetime |
| 3 | +import fcntl |
| 4 | +import json |
| 5 | +import threading |
| 6 | +import time |
| 7 | +from pathlib import Path |
| 8 | + |
| 9 | +from constants import TZ_INFO |
| 10 | + |
| 11 | + |
| 12 | +class CounterFile: |
| 13 | + def __init__(self, filepath: str, save_interval: int, save_threshold: int): |
| 14 | + """ |
| 15 | + Counter that saves to a file. |
| 16 | +
|
| 17 | + Args: |
| 18 | + filepath: The absolute file path to save the counter to. |
| 19 | + save_interval: How often to save to the file, in seconds |
| 20 | + save_threshold: How often to save to the file, in number of changes |
| 21 | + """ |
| 22 | + self.__counters: dict[str, int] = {} |
| 23 | + |
| 24 | + self.filepath = Path(filepath) |
| 25 | + self.save_interval = save_interval |
| 26 | + self.save_threshold = save_threshold |
| 27 | + self.lock = threading.Lock() |
| 28 | + self.create_time = datetime.datetime.now(TZ_INFO) |
| 29 | + self.last_save_time = self.create_time |
| 30 | + self.changes_since_last_save = 0 |
| 31 | + |
| 32 | + self._is_auto_save_enabled = save_interval > 0 |
| 33 | + |
| 34 | + # If the program shuts down, turn save one last time |
| 35 | + atexit.register(self.__save_to_file) |
| 36 | + |
| 37 | + self.start() |
| 38 | + |
| 39 | + def start(self): |
| 40 | + self.filepath.parent.mkdir(parents=True, exist_ok=True) |
| 41 | + save_data = { |
| 42 | + "counters": self.__counters, |
| 43 | + "last_save_time": self.last_save_time.isoformat(), |
| 44 | + } |
| 45 | + # Create file if it doesn't exist |
| 46 | + if not self.filepath.exists(): |
| 47 | + self.filepath.write_text(json.dumps(save_data, indent=2)) |
| 48 | + self.__save_to_file() |
| 49 | + else: |
| 50 | + # Otherwise check the file and load from it |
| 51 | + try: |
| 52 | + with Path.open(self.filepath) as f: |
| 53 | + fcntl.flock(f.fileno(), fcntl.LOCK_SH) |
| 54 | + try: |
| 55 | + data = json.load(f) |
| 56 | + self.__counters = data.get("counters", {}) |
| 57 | + finally: |
| 58 | + fcntl.flock(f.fileno(), fcntl.LOCK_UN) |
| 59 | + except (OSError, json.JSONDecodeError): |
| 60 | + self.__counters = {} |
| 61 | + if self._is_auto_save_enabled: |
| 62 | + self.daemon_thread = threading.Thread(target=self.__save_daemon, daemon=True) |
| 63 | + self.daemon_thread.start() |
| 64 | + |
| 65 | + def increment(self, key: str, amount: int = 1): |
| 66 | + with self.lock: |
| 67 | + self.__counters[key] = self.__counters.get(key, 0) + amount |
| 68 | + self.changes_since_last_save += 1 |
| 69 | + |
| 70 | + if self.changes_since_last_save >= self.save_threshold: |
| 71 | + self.__save_to_file() |
| 72 | + |
| 73 | + def get_all_counters(self) -> dict[str, int]: |
| 74 | + with self.lock: |
| 75 | + return self.__counters.copy() |
| 76 | + |
| 77 | + def __save_daemon(self): |
| 78 | + while self._is_auto_save_enabled: |
| 79 | + time.sleep(self.save_interval) |
| 80 | + if self.changes_since_last_save: |
| 81 | + self.__save_to_file() |
| 82 | + |
| 83 | + def __save_to_file(self): |
| 84 | + with self.lock: |
| 85 | + if not self.changes_since_last_save: |
| 86 | + return |
| 87 | + last_save_time = datetime.datetime.now(TZ_INFO) |
| 88 | + save_data = {"counters": self.__counters.copy(), "last_save_time": last_save_time.isoformat()} |
| 89 | + |
| 90 | + # Save to temp file and then move it |
| 91 | + temp_file = self.filepath.with_suffix(".tmp") |
| 92 | + try: |
| 93 | + with Path.open(temp_file, "w") as f: |
| 94 | + fcntl.flock(f.fileno(), fcntl.LOCK_EX) |
| 95 | + try: |
| 96 | + json.dump(save_data, f, indent=2) |
| 97 | + f.flush() |
| 98 | + finally: |
| 99 | + fcntl.flock(f.fileno(), fcntl.LOCK_UN) |
| 100 | + |
| 101 | + temp_file.replace(self.filepath) |
| 102 | + except OSError: |
| 103 | + print("Error saving counter file") |
| 104 | + return |
| 105 | + |
| 106 | + with self.lock: |
| 107 | + self.changes_since_last_save = 0 |
| 108 | + self.last_save_time = last_save_time |
| 109 | + |
| 110 | + def shutdown(self): |
| 111 | + self._is_auto_save_enabled = False |
| 112 | + if hasattr(self, "daemon_thread") and self.daemon_thread.is_alive(): |
| 113 | + self.daemon_thread.join(timeout=5) |
| 114 | + self.__save_to_file() |
0 commit comments