fix(statistic): 修复统计任务中因数据库记录格式问题导致的异常

在处理来自数据库的记录时,增加对记录类型的检查和时间戳格式的转换。确保即使记录不是预期的字典格式,或者时间戳字段为None或字符串格式,程序也能够安全处理,避免因`TypeError`或`AttributeError`导致整个统计任务中断(说真的这都一天了为什么还没人修)
This commit is contained in:
minecraft1024a
2025-08-16 21:33:40 +08:00
parent 618f6e474a
commit 26689061d6

View File

@@ -372,10 +372,19 @@ class StatisticOutputTask(AsyncTask):
model_class=LLMUsage,
filters={"timestamp": {"$gte": query_start_time}},
order_by="-timestamp"
)
) or []
for record in records:
record_timestamp = record['timestamp'] # 从字典中获取
if not isinstance(record, dict):
continue
record_timestamp = record.get('timestamp')
if isinstance(record_timestamp, str):
record_timestamp = datetime.fromisoformat(record_timestamp)
if not record_timestamp:
continue
for idx, (_, period_start) in enumerate(collect_period):
if record_timestamp >= period_start:
for period_key, _ in collect_period[idx:]:
@@ -420,7 +429,7 @@ class StatisticOutputTask(AsyncTask):
stats[period_key][COST_BY_MODULE][module_name] += cost
# 收集time_cost数据
time_cost = record.time_cost or 0.0
time_cost = record.get('time_cost') or 0.0
if time_cost > 0: # 只记录有效的time_cost
stats[period_key][TIME_COST_BY_TYPE][request_type].append(time_cost)
stats[period_key][TIME_COST_BY_USER][user_id].append(time_cost)
@@ -478,11 +487,22 @@ class StatisticOutputTask(AsyncTask):
model_class=OnlineTime,
filters={"end_timestamp": {"$gte": query_start_time}},
order_by="-end_timestamp"
)
) or []
for record in records:
record_end_timestamp = record['end_timestamp']
record_start_timestamp = record['start_timestamp']
if not isinstance(record, dict):
continue
record_end_timestamp = record.get('end_timestamp')
if isinstance(record_end_timestamp, str):
record_end_timestamp = datetime.fromisoformat(record_end_timestamp)
record_start_timestamp = record.get('start_timestamp')
if isinstance(record_start_timestamp, str):
record_start_timestamp = datetime.fromisoformat(record_start_timestamp)
if not record_end_timestamp or not record_start_timestamp:
continue
for idx, (_, period_boundary_start) in enumerate(collect_period):
if record_end_timestamp >= period_boundary_start:
@@ -523,10 +543,15 @@ class StatisticOutputTask(AsyncTask):
model_class=Messages,
filters={"time": {"$gte": query_start_timestamp}},
order_by="-time"
)
) or []
for message in records:
message_time_ts = message['time'] # This is a float timestamp
if not isinstance(message, dict):
continue
message_time_ts = message.get('time') # This is a float timestamp
if not message_time_ts:
continue
chat_id = None
chat_name = None