Download core/database.py from kikl/kookbot: direct link, hf CLI and curl.
- Browser
- Download file 2.34 kB
-
https://huggingface.co/spaces/kikl/kookbot/resolve/main/core/database.py
- Command line
-
hf download hf://spaces/kikl/kookbot/core/database.py
-
curl -L -o database.py https://huggingface.co/spaces/kikl/kookbot/resolve/main/core/database.py
2.34 kB
| from motor.motor_asyncio import AsyncIOMotorClient | |
| from core.config import logger, MONGO_URI, MONGO_DB_NAME | |
| class DatabaseManager: | |
| """MongoDB 连接管理""" | |
| def __init__(self): | |
| self.client = None | |
| self.users = None # 余额 | |
| self.ledger = None # 流水 | |
| self.checkins = None # 打卡记录 | |
| self.lifecycle = None # 进程启停记录,用于排查休眠/重启 | |
| async def connect(self): | |
| try: | |
| self.client = AsyncIOMotorClient( | |
| MONGO_URI, | |
| serverSelectionTimeoutMS=5000, | |
| maxPoolSize=5, | |
| minPoolSize=1, | |
| maxIdleTimeMS=30000, | |
| # 不加这个,Motor 会把写入的 aware datetime 读回来成 naive UTC, | |
| # 再一 astimezone 就会被当成本地时间,打卡时长直接算错。 | |
| tz_aware=True, | |
| ) | |
| db = self.client[MONGO_DB_NAME] | |
| self.users = db["users"] | |
| self.ledger = db["ledger"] | |
| self.checkins = db["checkins"] | |
| self.lifecycle = db["lifecycle"] | |
| await self.client.admin.command("ping") | |
| logger.info("[DB] MongoDB 连接成功 (%s)", MONGO_DB_NAME) | |
| # 余额查询走 _id 主键,天然有索引; | |
| # 流水和打卡列表按用户 + 时间倒序查,建复合索引。 | |
| await self.ledger.create_index([("user_id", 1), ("created_at", -1)]) | |
| await self.checkins.create_index([("date", -1), ("user_id", 1)]) | |
| # 幂等键唯一索引:同一笔操作(同一条消息)重复执行时, | |
| # 第二遍的 ledger 插入会撞唯一键失败,据此跳过 $inc。 | |
| # sparse 让不带幂等键的历史数据不受影响。 | |
| await self.ledger.create_index( | |
| [("idem_key", 1)], unique=True, sparse=True) | |
| # 启停记录保留 180 天就够排查了,TTL 自动清理 | |
| await self.lifecycle.create_index( | |
| [("at", 1)], expireAfterSeconds=180 * 24 * 3600) | |
| return True | |
| except Exception as e: | |
| logger.error("[DB] 连接失败: %s", e) | |
| return False | |
| def connected(self) -> bool: | |
| return self.client is not None | |
| db = DatabaseManager() | |