进一步优化 合理拆分文件和优化
This commit is contained in:
1 parent
ed76ec5da3
commit
fa5bb66d14
30 files changed
+3007
-2363
No files matched your search
@@ -1,176 +0,0 @@
|
||||
/**
|
||||
* Memory Diagnostics Tool
|
||||
* 诊断内存泄漏和高内存使用
|
||||
*/
|
||||
|
||||
const v8 = require('v8');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
/**
|
||||
* 生成堆快照
|
||||
*/
|
||||
function takeHeapSnapshot(filename) {
|
||||
const snapshotPath = path.join(__dirname, '..', 'logs', filename);
|
||||
|
||||
// 确保目录存在
|
||||
const dir = path.dirname(snapshotPath);
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
|
||||
const snapshot = v8.writeHeapSnapshot(snapshotPath);
|
||||
console.log(`[MemoryDiagnostics] Heap snapshot saved: ${snapshot}`);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取堆统计信息
|
||||
*/
|
||||
function getHeapStatistics() {
|
||||
const stats = v8.getHeapStatistics();
|
||||
return {
|
||||
totalHeapSize: (stats.total_heap_size / 1024 / 1024).toFixed(2) + ' MB',
|
||||
totalHeapSizeExecutable: (stats.total_heap_size_executable / 1024 / 1024).toFixed(2) + ' MB',
|
||||
totalPhysicalSize: (stats.total_physical_size / 1024 / 1024).toFixed(2) + ' MB',
|
||||
totalAvailableSize: (stats.total_available_size / 1024 / 1024).toFixed(2) + ' MB',
|
||||
usedHeapSize: (stats.used_heap_size / 1024 / 1024).toFixed(2) + ' MB',
|
||||
heapSizeLimit: (stats.heap_size_limit / 1024 / 1024).toFixed(2) + ' MB',
|
||||
mallocedMemory: (stats.malloced_memory / 1024 / 1024).toFixed(2) + ' MB',
|
||||
peakMallocedMemory: (stats.peak_malloced_memory / 1024 / 1024).toFixed(2) + ' MB',
|
||||
doesZapGarbage: stats.does_zap_garbage
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 打印堆统计信息
|
||||
*/
|
||||
function logHeapStatistics() {
|
||||
const stats = getHeapStatistics();
|
||||
console.log('\n[MemoryDiagnostics] Heap Statistics:');
|
||||
Object.entries(stats).forEach(([key, value]) => {
|
||||
console.log(` ${key}: ${value}`);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 强制垃圾回收并报告
|
||||
*/
|
||||
function forceGCAndReport() {
|
||||
if (!global.gc) {
|
||||
console.warn('[MemoryDiagnostics] GC not available. Run with --expose-gc');
|
||||
return null;
|
||||
}
|
||||
|
||||
const before = process.memoryUsage();
|
||||
const beforeRSS = before.rss / 1024 / 1024;
|
||||
const beforeHeap = before.heapUsed / 1024 / 1024;
|
||||
|
||||
console.log(`[MemoryDiagnostics] Before GC: RSS=${beforeRSS.toFixed(0)}MB, Heap=${beforeHeap.toFixed(0)}MB`);
|
||||
|
||||
// 执行多次 GC
|
||||
for (let i = 0; i < 5; i++) {
|
||||
global.gc();
|
||||
}
|
||||
|
||||
const after = process.memoryUsage();
|
||||
const afterRSS = after.rss / 1024 / 1024;
|
||||
const afterHeap = after.heapUsed / 1024 / 1024;
|
||||
|
||||
const rssReclaimed = beforeRSS - afterRSS;
|
||||
const heapReclaimed = beforeHeap - afterHeap;
|
||||
|
||||
console.log(`[MemoryDiagnostics] After GC: RSS=${afterRSS.toFixed(0)}MB, Heap=${afterHeap.toFixed(0)}MB`);
|
||||
console.log(`[MemoryDiagnostics] Reclaimed: RSS=${rssReclaimed.toFixed(0)}MB, Heap=${heapReclaimed.toFixed(0)}MB`);
|
||||
|
||||
return {
|
||||
before: { rss: beforeRSS, heap: beforeHeap },
|
||||
after: { rss: afterRSS, heap: afterHeap },
|
||||
reclaimed: { rss: rssReclaimed, heap: heapReclaimed }
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 检测可能的内存泄漏
|
||||
*/
|
||||
function detectMemoryLeak() {
|
||||
const usage = process.memoryUsage();
|
||||
const rss = usage.rss / 1024 / 1024;
|
||||
const heap = usage.heapUsed / 1024 / 1024;
|
||||
const external = usage.external / 1024 / 1024;
|
||||
|
||||
const issues = [];
|
||||
|
||||
// RSS 过高
|
||||
if (rss > 500) {
|
||||
issues.push({
|
||||
type: 'HIGH_RSS',
|
||||
severity: 'critical',
|
||||
message: `RSS is very high: ${rss.toFixed(0)}MB`,
|
||||
suggestion: 'Check for native memory leaks, large buffers, or file handles'
|
||||
});
|
||||
}
|
||||
|
||||
// Heap 过高
|
||||
if (heap > 200) {
|
||||
issues.push({
|
||||
type: 'HIGH_HEAP',
|
||||
severity: 'warning',
|
||||
message: `Heap usage is high: ${heap.toFixed(0)}MB`,
|
||||
suggestion: 'Check for object retention, closures, or large data structures'
|
||||
});
|
||||
}
|
||||
|
||||
// External 过高
|
||||
if (external > 100) {
|
||||
issues.push({
|
||||
type: 'HIGH_EXTERNAL',
|
||||
severity: 'warning',
|
||||
message: `External memory is high: ${external.toFixed(0)}MB`,
|
||||
suggestion: 'Check for Buffer allocations, native addons, or C++ objects'
|
||||
});
|
||||
}
|
||||
|
||||
// RSS 远大于 Heap(可能是 native 内存泄漏)
|
||||
if (rss > heap * 3) {
|
||||
issues.push({
|
||||
type: 'RSS_HEAP_MISMATCH',
|
||||
severity: 'critical',
|
||||
message: `RSS (${rss.toFixed(0)}MB) is much larger than Heap (${heap.toFixed(0)}MB)`,
|
||||
suggestion: 'Likely native memory leak. Check SQLite, Sharp, or other native modules'
|
||||
});
|
||||
}
|
||||
|
||||
return issues;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打印内存泄漏诊断
|
||||
*/
|
||||
function diagnoseMemoryLeak() {
|
||||
console.log('\n[MemoryDiagnostics] Running memory leak detection...\n');
|
||||
|
||||
const issues = detectMemoryLeak();
|
||||
|
||||
if (issues.length === 0) {
|
||||
console.log('✅ No obvious memory issues detected');
|
||||
} else {
|
||||
console.log(`⚠️ Found ${issues.length} potential issues:\n`);
|
||||
issues.forEach((issue, index) => {
|
||||
console.log(`${index + 1}. [${issue.severity.toUpperCase()}] ${issue.type}`);
|
||||
console.log(` ${issue.message}`);
|
||||
console.log(` 💡 ${issue.suggestion}\n`);
|
||||
});
|
||||
}
|
||||
|
||||
return issues;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
takeHeapSnapshot,
|
||||
getHeapStatistics,
|
||||
logHeapStatistics,
|
||||
forceGCAndReport,
|
||||
detectMemoryLeak,
|
||||
diagnoseMemoryLeak
|
||||
};
|
||||
@@ -1,63 +0,0 @@
|
||||
/**
|
||||
* Memory Statistics Utility
|
||||
* 显示详细的内存使用统计
|
||||
*/
|
||||
|
||||
function formatBytes(bytes) {
|
||||
return (bytes / 1024 / 1024).toFixed(2) + ' MB';
|
||||
}
|
||||
|
||||
function getMemoryStats() {
|
||||
const usage = process.memoryUsage();
|
||||
|
||||
return {
|
||||
heapUsed: usage.heapUsed,
|
||||
heapTotal: usage.heapTotal,
|
||||
rss: usage.rss,
|
||||
external: usage.external,
|
||||
arrayBuffers: usage.arrayBuffers,
|
||||
heapUsedMB: formatBytes(usage.heapUsed),
|
||||
heapTotalMB: formatBytes(usage.heapTotal),
|
||||
rssMB: formatBytes(usage.rss),
|
||||
externalMB: formatBytes(usage.external),
|
||||
arrayBuffersMB: formatBytes(usage.arrayBuffers)
|
||||
};
|
||||
}
|
||||
|
||||
function logMemoryStats(label = 'Memory') {
|
||||
const stats = getMemoryStats();
|
||||
console.log(`\n[${label}] Memory Statistics:`);
|
||||
console.log(` RSS (总内存): ${stats.rssMB}`);
|
||||
console.log(` Heap Used (堆使用): ${stats.heapUsedMB}`);
|
||||
console.log(` Heap Total (堆总量):${stats.heapTotalMB}`);
|
||||
console.log(` External (外部): ${stats.externalMB}`);
|
||||
console.log(` Array Buffers: ${stats.arrayBuffersMB}`);
|
||||
}
|
||||
|
||||
function getMemoryPressure() {
|
||||
const usage = process.memoryUsage();
|
||||
const heapUsedMB = usage.heapUsed / 1024 / 1024;
|
||||
const rssMB = usage.rss / 1024 / 1024;
|
||||
|
||||
let pressure = 'low';
|
||||
if (heapUsedMB > 200 || rssMB > 500) {
|
||||
pressure = 'critical';
|
||||
} else if (heapUsedMB > 100 || rssMB > 300) {
|
||||
pressure = 'high';
|
||||
} else if (heapUsedMB > 50 || rssMB > 150) {
|
||||
pressure = 'medium';
|
||||
}
|
||||
|
||||
return {
|
||||
level: pressure,
|
||||
heapUsedMB,
|
||||
rssMB
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getMemoryStats,
|
||||
logMemoryStats,
|
||||
getMemoryPressure,
|
||||
formatBytes
|
||||
};
|
||||
@@ -1,148 +0,0 @@
|
||||
/**
|
||||
* 缩略图迁移工具
|
||||
* 将旧结构的缩略图迁移到新的分片结构
|
||||
*
|
||||
* 旧结构:.flypic/thumbnails/hash.webp
|
||||
* 新结构:.flypic/thumbnails/ab/hash.webp (分片存储)
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
/**
|
||||
* 迁移单个素材库的缩略图
|
||||
* @param {string} libraryPath - 素材库路径
|
||||
* @returns {Object} 迁移结果统计
|
||||
*/
|
||||
async function migrateThumbnails(libraryPath) {
|
||||
const thumbnailsDir = path.join(libraryPath, '.flypic', 'thumbnails');
|
||||
|
||||
// 检查目录是否存在
|
||||
if (!fs.existsSync(thumbnailsDir)) {
|
||||
return { migrated: 0, skipped: 0, errors: 0, message: 'Thumbnails directory not found' };
|
||||
}
|
||||
|
||||
const stats = {
|
||||
migrated: 0,
|
||||
skipped: 0,
|
||||
errors: 0
|
||||
};
|
||||
|
||||
try {
|
||||
const entries = fs.readdirSync(thumbnailsDir, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
// 跳过已经是目录的(已经是新结构)
|
||||
if (entry.isDirectory()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 只处理 .webp 文件
|
||||
if (!entry.name.endsWith('.webp')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const oldPath = path.join(thumbnailsDir, entry.name);
|
||||
|
||||
// 提取 hash(去掉扩展名)
|
||||
const hash = entry.name.replace('.webp', '');
|
||||
|
||||
// 计算分片目录(使用前2个字符)
|
||||
const shard = hash.slice(0, 2);
|
||||
const shardDir = path.join(thumbnailsDir, shard);
|
||||
const newPath = path.join(shardDir, entry.name);
|
||||
|
||||
// 如果新路径已存在,跳过
|
||||
if (fs.existsSync(newPath)) {
|
||||
stats.skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// 创建分片目录
|
||||
if (!fs.existsSync(shardDir)) {
|
||||
fs.mkdirSync(shardDir, { recursive: true });
|
||||
}
|
||||
|
||||
// 移动文件
|
||||
fs.renameSync(oldPath, newPath);
|
||||
stats.migrated++;
|
||||
|
||||
console.log(`[Migrate] Moved: ${entry.name} -> ${shard}/${entry.name}`);
|
||||
} catch (error) {
|
||||
console.error(`[Migrate] Error migrating ${entry.name}:`, error.message);
|
||||
stats.errors++;
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[Migrate] Complete for ${libraryPath}:`, stats);
|
||||
return stats;
|
||||
} catch (error) {
|
||||
console.error(`[Migrate] Error reading thumbnails directory:`, error);
|
||||
return { ...stats, message: error.message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否需要迁移
|
||||
* @param {string} libraryPath - 素材库路径
|
||||
* @returns {boolean} 是否需要迁移
|
||||
*/
|
||||
function needsMigration(libraryPath) {
|
||||
const thumbnailsDir = path.join(libraryPath, '.flypic', 'thumbnails');
|
||||
|
||||
if (!fs.existsSync(thumbnailsDir)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const entries = fs.readdirSync(thumbnailsDir, { withFileTypes: true });
|
||||
|
||||
// 检查是否有直接在 thumbnails 目录下的 .webp 文件
|
||||
for (const entry of entries) {
|
||||
if (entry.isFile() && entry.name.endsWith('.webp')) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
} catch (error) {
|
||||
console.error(`[Migrate] Error checking migration need:`, error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量迁移多个素材库
|
||||
* @param {Array} libraries - 素材库列表
|
||||
* @returns {Object} 总体迁移统计
|
||||
*/
|
||||
async function migrateAllLibraries(libraries) {
|
||||
const totalStats = {
|
||||
migrated: 0,
|
||||
skipped: 0,
|
||||
errors: 0,
|
||||
librariesProcessed: 0
|
||||
};
|
||||
|
||||
for (const library of libraries) {
|
||||
if (needsMigration(library.path)) {
|
||||
console.log(`[Migrate] Processing library: ${library.name}`);
|
||||
const stats = await migrateThumbnails(library.path);
|
||||
|
||||
totalStats.migrated += stats.migrated;
|
||||
totalStats.skipped += stats.skipped;
|
||||
totalStats.errors += stats.errors;
|
||||
totalStats.librariesProcessed++;
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[Migrate] Total stats:`, totalStats);
|
||||
return totalStats;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
migrateThumbnails,
|
||||
needsMigration,
|
||||
migrateAllLibraries
|
||||
};
|
||||
Reference in new issue
Block a user