File size: 2,342 Bytes
e6d4151 0163d21 e6d4151 0163d21 e6d4151 0163d21 53c658e e6d4151 0163d21 53c658e 0163d21 c987ed8 53c658e e6d4151 0163d21 e6d4151 0163d21 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | 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
@property
def connected(self) -> bool:
return self.client is not None
db = DatabaseManager()
|