refactor(logging): remove agent logging from various components to streamline code and improve maintainability
Publish Fast Tabler Docker image / build-and-push-fast (push) Successful in 1m49s

This commit is contained in:
2026-02-24 13:53:41 +07:00
parent 8035b7751f
commit b56df61c8f
11 changed files with 197 additions and 146 deletions
-44
View File
@@ -7,25 +7,6 @@ const { sendError } = require('../middleware/errorHandler');
const { decrypt } = require('../utils/encryption');
const { readServersFromS3 } = require('./serversRoutes');
const { createRosClient } = require('../services/mikrotikApplyService');
const DEBUG_ENDPOINT = 'http://192.168.10.2:7343/ingest/aa002dd6-6968-4a35-b09d-f05302d83266';
function sendDebugLog(location, message, data, hypothesisId = 'H_RS_BACKEND_SLOW') {
// #region agent log
fetch(DEBUG_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Debug-Session-Id': '378b5f' },
body: JSON.stringify({
sessionId: '378b5f',
runId: 'resource-stats-investigation',
hypothesisId,
location,
message,
data: data || {},
timestamp: Date.now(),
}),
}).catch(() => {});
// #endregion
}
function getMikrotikCredentials(server) {
if (!server || (server.type !== 'jumphost' && server.type !== 'home')) return null;
@@ -96,7 +77,6 @@ function parseResource(raw) {
* Внутренняя функция: возвращает данные по ресурсам роутеров (без HTTP).
*/
async function getResourceStatsData() {
const startedAt = Date.now();
const servers = await readServersFromS3();
const routers = (Array.isArray(servers) ? servers : []).filter(
(s) =>
@@ -104,14 +84,9 @@ async function getResourceStatsData() {
(String(s.type || '').toLowerCase() === 'jumphost' ||
String(s.type || '').toLowerCase() === 'home')
);
sendDebugLog('backend/routes/resourceStatsRoutes.js:getResourceStatsData-routers', 'Resource stats routers loaded', {
serversCount: Array.isArray(servers) ? servers.length : 0,
routersCount: routers.length,
});
const results = await Promise.all(
routers.map(async (server) => {
const routerStartedAt = Date.now();
const serverId = server.id || server.dns || server.ip;
const name = server.name || server.dns || server.ip || serverId;
const host = server.mikrotikHost || server.ip || server.dns;
@@ -123,7 +98,6 @@ async function getResourceStatsData() {
name,
host,
groupKey: server.groupKey || null,
durationMs: Date.now() - routerStartedAt,
error: 'MikroTik API не настроен или нет пароля',
resource: null,
};
@@ -139,7 +113,6 @@ async function getResourceStatsData() {
name,
host,
groupKey: server.groupKey || null,
durationMs: Date.now() - routerStartedAt,
error: null,
resource,
};
@@ -150,7 +123,6 @@ async function getResourceStatsData() {
name,
host,
groupKey: server.groupKey || null,
durationMs: Date.now() - routerStartedAt,
error: msg,
resource: null,
};
@@ -158,22 +130,6 @@ async function getResourceStatsData() {
})
);
const totalDurationMs = Date.now() - startedAt;
const slowRouters = results
.map((r) => ({
serverId: r.serverId,
durationMs: Number(r.durationMs || 0),
hasError: Boolean(r.error),
}))
.sort((a, b) => b.durationMs - a.durationMs)
.slice(0, 5);
sendDebugLog('backend/routes/resourceStatsRoutes.js:getResourceStatsData-done', 'Resource stats aggregate timing', {
totalDurationMs,
routersCount: results.length,
errorsCount: results.filter((r) => Boolean(r.error)).length,
slowRouters,
});
return { routers: results };
}
-3
View File
@@ -148,9 +148,6 @@ function createTextDataPOST(s3Key, formatLine, validate, validateItem = null) {
} catch {}
if (current && (ifMatch || etag) && current !== String(ifMatch || etag)) {
// #region agent log
fetch('http://192.168.10.2:7343/ingest/aa002dd6-6968-4a35-b09d-f05302d83266',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'378b5f'},body:JSON.stringify({sessionId:'378b5f',runId:'baseline',hypothesisId:'H2',location:'backend/routes/textDataRoutes.js:etag-mismatch',message:'ETag mismatch detected in text POST',data:{s3Key:String(s3Key||''),currentEtag:String(current||''),providedEtag:String(ifMatch||etag||'')},timestamp:Date.now()})}).catch(()=>{});
// #endregion
const { headMeta } = require('../services/s3Service');
const meta = await headMeta(s3Key);
return sendError(res, 412, 'Precondition Failed: ETag mismatch', 'E_ETAG_MISMATCH', {
-9
View File
@@ -412,18 +412,12 @@ app.post('/api/server-filters/:serverId', serverConfigsRoutes.postServerFilters)
// === LOCKS ===
app.get('/api/locks/:resource', (req, res) => {
const status = getLockStatus(req.params.resource);
// #region agent log
fetch('http://192.168.10.2:7343/ingest/aa002dd6-6968-4a35-b09d-f05302d83266',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'378b5f'},body:JSON.stringify({sessionId:'378b5f',runId:'baseline',hypothesisId:'H4',location:'backend/server.js:locks-get',message:'Lock status requested',data:{resource:String(req?.params?.resource||''),locked:Boolean(status?.locked)},timestamp:Date.now()})}).catch(()=>{});
// #endregion
res.json(status);
});
app.post('/api/locks/:resource', (req, res) => {
const { owner = 'anonymous', ttlSeconds = 120 } = req.body || {};
const result = acquireLock(req.params.resource, owner, ttlSeconds);
// #region agent log
fetch('http://192.168.10.2:7343/ingest/aa002dd6-6968-4a35-b09d-f05302d83266',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'378b5f'},body:JSON.stringify({sessionId:'378b5f',runId:'baseline',hypothesisId:'H4',location:'backend/server.js:locks-post',message:'Lock acquire attempted',data:{resource:String(req?.params?.resource||''),owner:String(owner||''),success:Boolean(result?.success),locked:Boolean(result?.locked)},timestamp:Date.now()})}).catch(()=>{});
// #endregion
if (!result.success) {
return sendError(res, 423, 'Resource is locked by another user', 'E_RESOURCE_LOCKED', {
owner: result.owner,
@@ -435,9 +429,6 @@ app.post('/api/locks/:resource', (req, res) => {
app.delete('/api/locks/:resource', (req, res) => {
const result = releaseLock(req.params.resource);
// #region agent log
fetch('http://192.168.10.2:7343/ingest/aa002dd6-6968-4a35-b09d-f05302d83266',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'378b5f'},body:JSON.stringify({sessionId:'378b5f',runId:'baseline',hypothesisId:'H4',location:'backend/server.js:locks-delete',message:'Lock released',data:{resource:String(req?.params?.resource||''),released:Boolean(result?.released)},timestamp:Date.now()})}).catch(()=>{});
// #endregion
res.json(result);
});
-45
View File
@@ -14,25 +14,6 @@ const NETWORK_MAP_CACHE_KEY = 'network-map-cache/latest.json';
const DEFAULT_INTERVAL_MINUTES = 5;
const DEFAULT_LOG_MAX_LINES = 500;
const DEBUG_ENDPOINT = 'http://192.168.10.2:7343/ingest/aa002dd6-6968-4a35-b09d-f05302d83266';
function sendDebugLog(location, message, data, hypothesisId = 'H_STARTUP_SPEEDTEST') {
// #region agent log
fetch(DEBUG_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Debug-Session-Id': '378b5f' },
body: JSON.stringify({
sessionId: '378b5f',
runId: 'nm-startup-investigation',
hypothesisId,
location,
message,
data: data || {},
timestamp: Date.now(),
}),
}).catch(() => {});
// #endregion
}
/** Кольцевой буфер логов */
class LogBuffer {
@@ -369,7 +350,6 @@ function getSettingsFromUiSettings(uiSettings) {
function initNetworkMapScheduler(logger, port) {
const log = logger || console;
const baseUrl = `http://127.0.0.1:${port}`;
sendDebugLog('backend/services/networkMapScheduler.js:init', 'initNetworkMapScheduler called', { port, baseUrl });
async function tick(source = 'interval') {
lastScheduledRunAt = Date.now();
@@ -381,22 +361,10 @@ function initNetworkMapScheduler(logger, port) {
return;
}
const settings = getSettingsFromUiSettings(uiSettings);
sendDebugLog('backend/services/networkMapScheduler.js:tick-settings', 'Tick evaluated settings', {
source,
enabled: settings.enabled,
intervalMinutes: settings.intervalMinutes,
runPing: settings.runPing,
runSpeedTest: settings.runSpeedTest,
});
if (!settings.enabled) return;
logBuffer.setMaxLines(settings.logMaxLines);
logBuffer.push('--- Запуск по расписанию ---');
sendDebugLog('backend/services/networkMapScheduler.js:tick-runjob', 'Tick starts runJob', {
source,
runPing: settings.runPing,
runSpeedTest: settings.runSpeedTest,
});
runJob({
baseUrl,
runPing: settings.runPing,
@@ -421,13 +389,6 @@ function initNetworkMapScheduler(logger, port) {
return;
}
const settings = getSettingsFromUiSettings(uiSettings);
sendDebugLog('backend/services/networkMapScheduler.js:schedule-settings', 'Schedule loaded settings', {
enabled: settings.enabled,
intervalMinutes: settings.intervalMinutes,
runPing: settings.runPing,
runSpeedTest: settings.runSpeedTest,
logMaxLines: settings.logMaxLines,
});
if (!settings.enabled) {
log.info({ component: 'network-map-scheduler' }, 'Scheduler disabled in settings');
return;
@@ -440,12 +401,6 @@ function initNetworkMapScheduler(logger, port) {
settings.intervalMinutes
);
schedulerTimer = setInterval(() => tick('interval'), intervalMs);
// #region agent log
sendDebugLog('backend/services/networkMapScheduler.js:schedule-startup-tick-skipped', 'Startup delayed tick skipped', {
reason: 'disabled_to_avoid_immediate_speedtest_after_restart',
intervalMs,
});
// #endregion
}
schedule();