81 lines
2.4 KiB
TypeScript
81 lines
2.4 KiB
TypeScript
// server/utils/runtimeState.ts - 服务启动时间和最近问答记录的内存状态
|
|
import { answerCache } from "~~/server/utils/cache";
|
|
import { serverEnv } from "~~/server/utils/env";
|
|
|
|
/** 最近问答记录,沿用旧 Python 服务 dashboard/stats 的内存记录语义 */
|
|
export interface QaRecord {
|
|
/** 本地可读时间,方便后续如果恢复 dashboard 时直接展示 */
|
|
time: string;
|
|
/** ISO 时间,方便机器处理和排序 */
|
|
timestamp: string;
|
|
/** 题目正文 */
|
|
question: string;
|
|
/** 题型 */
|
|
type: string;
|
|
/** 选项文本 */
|
|
options: string;
|
|
/** 最终返回给 OCS 的答案 */
|
|
answer: string;
|
|
}
|
|
|
|
/** 只保留最近 100 条,避免长时间运行后内存无限增长 */
|
|
const MAX_RECORDS = 100;
|
|
/** 进程启动时间,用于 `/api/stats` 返回 uptime */
|
|
const startTime = Date.now();
|
|
/** 进程内问答记录;服务重启或多实例部署时不会共享 */
|
|
const qaRecords: QaRecord[] = [];
|
|
|
|
/** 对外展示的服务版本,和 README/API 文档保持一致 */
|
|
export const SERVICE_VERSION = "1.1.0";
|
|
|
|
/** 格式化成本地 `YYYY-MM-DD HH:mm:ss`,对齐旧 Python 服务记录格式 */
|
|
const formatLocalDateTime = (date: Date) => {
|
|
const pad = (value: number) => value.toString().padStart(2, "0");
|
|
|
|
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(
|
|
date.getDate()
|
|
)} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(
|
|
date.getSeconds()
|
|
)}`;
|
|
};
|
|
|
|
/**
|
|
* 追加一条问答记录
|
|
*
|
|
* 记录只用于统计和未来可能恢复的 dashboard,不作为题库持久化数据
|
|
*/
|
|
export const addQaRecord = (record: Omit<QaRecord, "time" | "timestamp">) => {
|
|
const now = new Date();
|
|
|
|
qaRecords.push({
|
|
time: formatLocalDateTime(now),
|
|
timestamp: now.toISOString(),
|
|
...record
|
|
});
|
|
|
|
if (qaRecords.length > MAX_RECORDS) {
|
|
qaRecords.shift();
|
|
}
|
|
};
|
|
|
|
/**
|
|
* 获取最近问答记录
|
|
*
|
|
* 返回副本并按“最新在前”排序,避免 API handler 或前端展示逻辑误改内存原数组
|
|
*/
|
|
export const getQaRecords = () => {
|
|
return [...qaRecords].reverse();
|
|
};
|
|
|
|
/** 生成 `/api/stats` 响应,实时计算 uptime 和有效缓存数量 */
|
|
export const getRuntimeStats = () => {
|
|
return {
|
|
version: SERVICE_VERSION,
|
|
uptime: (Date.now() - startTime) / 1000,
|
|
model: serverEnv.openAiModel,
|
|
cache_enabled: serverEnv.enableCache,
|
|
cache_size: answerCache?.size() ?? 0,
|
|
qa_records_count: qaRecords.length
|
|
};
|
|
};
|