|
| 1 | +from collections import deque |
| 2 | +from datetime import datetime |
| 3 | +import json |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | +from nonebot import get_driver |
| 7 | +from nonebot.adapters import Bot |
| 8 | +from nonebot.log import logger |
| 9 | +from nonebot_plugin_apscheduler import scheduler |
| 10 | +import nonebot_plugin_localstore as store |
| 11 | +from pydantic import BaseModel, ValidationError |
| 12 | + |
| 13 | +from .config import plugin_config |
| 14 | +from .cooldown import FixWindowUsage, SlidingWindowUsage, _FixWindowCooldownDict, _SlidingWindowCooldownDict, _tz |
| 15 | + |
| 16 | +driver = get_driver() |
| 17 | +plugin_data_file: Path = store.get_plugin_data_file("limiter_data.json") |
| 18 | + |
| 19 | + |
| 20 | +class PersistData(BaseModel): |
| 21 | + class FixWindowSet(BaseModel): |
| 22 | + start_time: int |
| 23 | + available: int |
| 24 | + |
| 25 | + fix_window: dict[str, dict[str, FixWindowSet]] | None = None |
| 26 | + |
| 27 | + class SlidingWindowSet(BaseModel): |
| 28 | + timestamps: list[int] |
| 29 | + |
| 30 | + sliding_window: dict[str, dict[str, SlidingWindowSet]] | None = None |
| 31 | + |
| 32 | + |
| 33 | +def load_usage_data() -> None: |
| 34 | + """加载本地存储的用量数据""" |
| 35 | + |
| 36 | + if not plugin_data_file.exists(): |
| 37 | + return |
| 38 | + try: |
| 39 | + data = PersistData.model_validate_json(plugin_data_file.read_text()) |
| 40 | + except ValidationError: |
| 41 | + logger.warning("Failed to load previous usage data (ValidationError), will ignore it.") |
| 42 | + return |
| 43 | + |
| 44 | + if data.fix_window is not None: |
| 45 | + for name, usage_set in data.fix_window.items(): |
| 46 | + if name not in _FixWindowCooldownDict: |
| 47 | + _FixWindowCooldownDict[name] = {} |
| 48 | + bucket = _FixWindowCooldownDict[name] |
| 49 | + for _id, usage in usage_set.items(): |
| 50 | + bucket[_id] = FixWindowUsage( |
| 51 | + start_time=datetime.fromtimestamp(usage.start_time, tz=_tz), |
| 52 | + available=usage.available, |
| 53 | + ) |
| 54 | + |
| 55 | + if data.sliding_window is not None: |
| 56 | + for name, usage_set in data.sliding_window.items(): |
| 57 | + if name not in _SlidingWindowCooldownDict: |
| 58 | + _SlidingWindowCooldownDict[name] = {} |
| 59 | + bucket = _SlidingWindowCooldownDict[name] |
| 60 | + for _id, usage in usage_set.items(): |
| 61 | + bucket[_id] = SlidingWindowUsage(timestamps=deque(datetime.fromtimestamp(t, tz=_tz) for t in usage.timestamps)) |
| 62 | + |
| 63 | + logger.info("Loaded previous usage data.") |
| 64 | + |
| 65 | + |
| 66 | +def save_usage_data() -> None: |
| 67 | + """保存用量数据到本地""" |
| 68 | + |
| 69 | + j = {"fix_window": {}, "sliding_window": {}} |
| 70 | + |
| 71 | + for name, usage_set in _FixWindowCooldownDict.items(): |
| 72 | + j["fix_window"][name] = { |
| 73 | + _id: { |
| 74 | + "start_time": int(usage.start_time.timestamp()), |
| 75 | + "available": usage.available, |
| 76 | + } |
| 77 | + for _id, usage in usage_set.items() |
| 78 | + } |
| 79 | + |
| 80 | + for name, usage_set in _SlidingWindowCooldownDict.items(): |
| 81 | + j["sliding_window"][name] = { |
| 82 | + _id: { |
| 83 | + "timestamps": [int(t.timestamp()) for t in usage.timestamps], |
| 84 | + } |
| 85 | + for _id, usage in usage_set.items() |
| 86 | + } |
| 87 | + |
| 88 | + plugin_data_file.write_text(json.dumps(j)) |
| 89 | + |
| 90 | +@driver.on_startup |
| 91 | +def _startup() -> None: |
| 92 | + if not plugin_config.cooldown_enable_persistence: |
| 93 | + return |
| 94 | + |
| 95 | + load_usage_data() |
| 96 | + scheduler.add_job(save_usage_data, "interval", seconds=plugin_config.cooldown_save_interval) |
| 97 | + if not scheduler.running: |
| 98 | + scheduler.start() |
| 99 | + |
| 100 | + |
| 101 | +@driver.on_bot_disconnect |
| 102 | +def _disconnect_save(bot: Bot) -> None: |
| 103 | + if not plugin_config.cooldown_enable_persistence: |
| 104 | + return |
| 105 | + |
| 106 | + save_usage_data() |
| 107 | + |
| 108 | + |
| 109 | +@driver.on_shutdown |
| 110 | +def _shutdown_save() -> None: |
| 111 | + if not plugin_config.cooldown_enable_persistence: |
| 112 | + return |
| 113 | + |
| 114 | + save_usage_data() |
0 commit comments