accounting_automation: журнал заданий и запросов (включён логгер Fastify), журнал не больше 10 МБ; планы тестирования для Юрия и Насти
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import Fastify, { type FastifyInstance } from "fastify";
|
||||
import type { Pool } from "khb_common";
|
||||
import Fastify, { type FastifyBaseLogger, type FastifyInstance } from "fastify";
|
||||
import type { Logger, Pool } from "khb_common";
|
||||
import { registerAssistantRoutes } from "./assistant-http.js";
|
||||
import { registerChargebackRoutes } from "./chargeback-http.js";
|
||||
import { registerMcp } from "./mcp.js";
|
||||
@@ -40,16 +40,32 @@ export interface ApiDeps {
|
||||
jobs: JobHandlers;
|
||||
/** Текст instructions для MCP (из p-mcp-instructions.md); не задан - встроенный. */
|
||||
mcpInstructions?: string;
|
||||
/** Журнал сервиса (pino): запуски и итоги заданий, служебные запросы. Не задан - ничего не пишется (тесты). */
|
||||
log?: Logger;
|
||||
}
|
||||
|
||||
/** Итог задания для журнала: не длиннее 2000 символов. */
|
||||
const clipForLog = (v: unknown): unknown => {
|
||||
const t = JSON.stringify(v ?? null);
|
||||
return t.length > 2000 ? { truncated: t.slice(0, 2000) } : v ?? null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Служебные ручки закрыты токеном сервиса (`accounting_automation.http.token`); /healthz открыт.
|
||||
* /mcp - отдельная аутентификация (токены сотрудников и Keycloak), наружу публикуется через nginx только он.
|
||||
*/
|
||||
export function buildApi(deps: ApiDeps): FastifyInstance {
|
||||
const app = Fastify();
|
||||
const app: FastifyInstance = deps.log
|
||||
? (Fastify({ loggerInstance: deps.log as unknown as FastifyBaseLogger, disableRequestLogging: true }) as unknown as FastifyInstance)
|
||||
: Fastify();
|
||||
const running = new Set<string>();
|
||||
|
||||
// Журнал запросов (без тел и заголовков, чтобы не попали токены и данные). /mcp пишется в acc_mcp_log, /healthz шумит.
|
||||
app.addHook("onResponse", async (req, reply) => {
|
||||
const path = req.url.split("?")[0]!;
|
||||
if (path === "/healthz" || path === "/mcp") return;
|
||||
req.log.info({ method: req.method, path, status: reply.statusCode, ms: Math.round(reply.elapsedTime) }, "запрос");
|
||||
});
|
||||
app.addHook("onRequest", async (req, reply) => {
|
||||
const path = req.url.split("?")[0]!;
|
||||
if (path === "/healthz" || path === "/mcp" || path.startsWith("/.well-known/")) return;
|
||||
@@ -70,9 +86,11 @@ export function buildApi(deps: ApiDeps): FastifyInstance {
|
||||
if (running.has(name)) return reply.code(409).send({ error: "already_running" });
|
||||
running.add(name);
|
||||
const exec = async (): Promise<unknown> => {
|
||||
const startedAt = Date.now();
|
||||
req.log.info({ job: name }, "задание запущено");
|
||||
try {
|
||||
const result = await handler();
|
||||
req.log.info({ job: name, result }, "задание выполнено");
|
||||
req.log.info({ job: name, ms: Date.now() - startedAt, result: clipForLog(result) }, "задание выполнено");
|
||||
return result;
|
||||
} finally {
|
||||
running.delete(name);
|
||||
|
||||
@@ -73,6 +73,7 @@ const app = buildApi({
|
||||
pool,
|
||||
settings: s,
|
||||
mcpInstructions,
|
||||
log,
|
||||
jobs: {
|
||||
"invoices-mail": async () => {
|
||||
if (!auth || !drive || !s.google) throw new Error("не настроены google (ключ сервисного аккаунта, rootFolderId)");
|
||||
|
||||
@@ -711,7 +711,8 @@ const clip = (v: unknown, n = 2000): unknown => {
|
||||
return t.length > n ? { truncated: t.slice(0, n) } : v ?? null;
|
||||
};
|
||||
|
||||
export const MCP_LOG_KEEP = 100000;
|
||||
/** Около 1 КБ на запись (args и результат усечены): 10 000 записей укладываются примерно в 10 МБ. */
|
||||
export const MCP_LOG_KEEP = 10000;
|
||||
let logWrites = 0;
|
||||
|
||||
/** Автоочистка журнала: оставляет последние keep записей, давние удаляет. Возвращает число удалённых. */
|
||||
|
||||
Reference in New Issue
Block a user