- 客户端解析上游 usage(含 DeepSeek 缓存命中/未命中),跨重试累加 - 新增计价表(三档单价 + 峰谷时段),费用在结算时冻结 - 新增用量上报与本地 outbox 重试;4xx 判定为确定性拒绝,不无限重试 - 面板补充 Token/费用/调用次数与计价快照 - 顺带修复面板内联脚本转义错误(模板字面量吃掉 \n 与 \',面板一直空白)
59 lines
2.0 KiB
TypeScript
59 lines
2.0 KiB
TypeScript
import { readFileSync } from "node:fs";
|
|
import { fileURLToPath } from "node:url";
|
|
import { dirname, resolve } from "node:path";
|
|
import Fastify from "fastify";
|
|
import { aiRoutes } from "./routes/ai.js";
|
|
import { adminRoutes } from "./admin/index.js";
|
|
import { usageReporter } from "./admin/reporter.js";
|
|
|
|
// ===== 加载 .env(零依赖,兼容 dev/start 两种启动方式)=====
|
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
const envPath = resolve(__dirname, "..", ".env");
|
|
try {
|
|
for (const line of readFileSync(envPath, "utf-8").split(/\r?\n/)) {
|
|
const trimmed = line.trim();
|
|
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
const eq = trimmed.indexOf("=");
|
|
if (eq === -1) continue;
|
|
const k = trimmed.slice(0, eq).trim();
|
|
const v = trimmed.slice(eq + 1).trim();
|
|
if (k && !(k in process.env)) process.env[k] = v;
|
|
}
|
|
} catch {
|
|
// .env not found, use system environment
|
|
}
|
|
|
|
const app = Fastify({
|
|
logger: {
|
|
level: "info",
|
|
redact: ["req.headers.authorization"], // 永不记录密钥
|
|
},
|
|
connectionTimeout: 180_000, // 3 min
|
|
// 安全-03:请求体上限。抓取标题与 AI 任务参数都是小报文,
|
|
// 没有上限时超大 body 可以打爆内存。
|
|
bodyLimit: Number(process.env.LPT_AI_BODY_LIMIT_BYTES ?? 256 * 1024),
|
|
});
|
|
|
|
await app.register(aiRoutes);
|
|
await app.register(adminRoutes);
|
|
|
|
// 用量上报(lpt-ai → lpt-be):未配置 LPT_AI_REPORT_URL 时为空操作。
|
|
// 必须放在 .env 加载之后:ESM 的 import 先于本文件顶层代码执行,
|
|
// 在模块顶层读环境变量永远读不到 .env 里的值。
|
|
if (usageReporter.isConfigured()) {
|
|
usageReporter.start();
|
|
app.log.info("用量上报已启用,待上报条数 " + usageReporter.pendingCount());
|
|
} else {
|
|
app.log.info("未配置 LPT_AI_REPORT_URL,用量只保留在本地面板(无长期账本)");
|
|
}
|
|
|
|
const port = Number(process.env.PORT ?? 5199);
|
|
|
|
try {
|
|
await app.listen({ port, host: "0.0.0.0" });
|
|
app.log.info(`lpt-ai 服务已启动,端口 ${port}`);
|
|
} catch (err) {
|
|
app.log.error(err);
|
|
process.exit(1);
|
|
}
|